-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker-create-postgresql
More file actions
436 lines (347 loc) · 11.6 KB
/
docker-create-postgresql
File metadata and controls
436 lines (347 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#!/bin/bash
LANG=C
set -euo pipefail
cmdname="$(basename "$0")"
newtmpdir="$(mktemp -d /tmp/${cmdname}.XXXXXX)"
user="$(whoami)"
OS="$(uname)"
[ "${user}" != "root" ] && echo "sudo ${cmdname}" && exit 1
cleanup () {
rm -rf "${newtmpdir}"
}
trap 'cleanup' EXIT
trap 'cleanup' SIGTERM
docker_bin="$(command -v docker || true)"
if [ -z "$docker_bin" ]; then
echo "Docker not installed. Proceed with install? (CTRL+C to Abort)"
echo "or run install manually: apt-get -y install docker-ce"
read -r _
apt-get -y install docker-ce
fi
usage() {
cat <<EOF
Usage: ${cmdname}
Interactive script to download and setup PostgreSQL docker configuration.
- Asks for PostgreSQL PORT and IMAGE TAG.
- Asks bind address: 127.0.0.1 / 0.0.0.0 / auto external IPv4.
- Creates persistent data dir under /var/lib/postgresql-<PORT>/data.
- Starts docker container with restart unless-stopped.
- Adjusts basic memory settings via -c on postgres.
- Adds entry to ~/.pgpass.
- Optionally sets up daily pg_dumpall backup via cron into /backup/<hostname>/.
No external postgresql.conf is mounted; container uses its own default config.
EOF
}
case "${1:-}" in
-h|--help)
usage
exit 0
;;
esac
# -------------------------
# Helpers
# -------------------------
get_total_mem_bytes_linux() {
awk '/MemTotal:/ {print $2 * 1024}' /proc/meminfo 2>/dev/null || echo 0
}
get_total_mem_bytes_darwin() {
sysctl -n hw.memsize 2>/dev/null || echo 0
}
get_total_mem_bytes() {
if [ "$OS" = "Darwin" ]; then
get_total_mem_bytes_darwin
else
get_total_mem_bytes_linux
fi
}
bytes_to_mb() { echo $(( $1 / 1024 / 1024 )); }
bytes_to_gb() { echo $(( $1 / 1024 / 1024 / 1024 )); }
detect_primary_ipv4() {
local primary=""
if command -v ip >/dev/null 2>&1; then
primary="$(ip route get 1.1.1.1 2>/dev/null | awk '/src/ {for(i=1;i<=NF;i++) if ($i=="src") {print $(i+1); exit}}' || true)"
fi
if [ -z "$primary" ]; then
primary="$(hostname -I 2>/dev/null | awk '{print $1}' || true)"
fi
echo "${primary:-}"
}
detect_target_home() {
if [ "$OS" = "Darwin" ]; then
eval echo "~${SUDO_USER:-$user}"
return
fi
if [ -n "${SUDO_USER:-}" ] && [ -d "/home/${SUDO_USER}" ]; then
echo "/home/${SUDO_USER}"
else
eval echo "~${SUDO_USER:-$user}"
fi
}
# -------------------------
# Input: PORT
# -------------------------
echo "Please enter database PORT (eg 5432), CTRL+C to abort: "
read -r docker_port
[ -z "${docker_port}" ] && echo "Error: Empty port!" && exit 1
if command -v lsof >/dev/null 2>&1; then
if lsof -i:"${docker_port}" 2>/dev/null | grep -q LISTEN; then
echo "ERROR: Port ${docker_port} already in use!"
lsof -i:"${docker_port}" 2>/dev/null | grep LISTEN || true
exit 1
fi
else
echo "Warning: lsof not found, skipping port check."
fi
# -------------------------
# Input: BIND address
# -------------------------
primary_ip="$(detect_primary_ipv4)"
echo
echo "Choose bind address for published port ${docker_port}:"
echo " 1) Local only (127.0.0.1)"
echo " 2) All IPv4 (0.0.0.0)"
if [ -n "$primary_ip" ]; then
echo " 3) Primary external (${primary_ip})"
else
echo " 3) Primary external (auto-detect failed; will ask)"
fi
echo "Enter choice [1-3] (default 1): "
read -r bind_choice
bind_choice="${bind_choice:-1}"
bind_ip="127.0.0.1"
case "$bind_choice" in
1)
bind_ip="127.0.0.1"
;;
2)
bind_ip="0.0.0.0"
;;
3)
if [ -z "$primary_ip" ]; then
echo "Enter external IPv4 to bind (eg 203.0.113.10): "
read -r primary_ip
[ -z "$primary_ip" ] && echo "Error: Empty IP!" && exit 1
fi
bind_ip="$primary_ip"
;;
*)
echo "Error: Unknown choice!"
exit 1
;;
esac
# -------------------------
# Input: VERSION/TAG
# -------------------------
echo
echo "Available common PostgreSQL tags (examples):"
echo " 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, latest"
echo "You can also enter full tags like 16-alpine if you want."
echo "Please enter database IMAGE TAG (default latest), CTRL+C to abort: "
read -r docker_pgversion
docker_pgversion="${docker_pgversion:-latest}"
# -------------------------
# Names/paths/password
# -------------------------
docker_superuser="postgres"
docker_servicename="postgresql-${docker_port}"
# Safe password generation with pipefail
docker_pass="$(head -c 128 /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 14 || true)"
if [ -z "$docker_pass" ]; then
docker_pass="$(date +%s%N | sha256sum | awk '{print $1}' | head -c 14)"
fi
base_path="/var/lib/${docker_servicename}"
data_path="${base_path}/data"
mkdir -p "${data_path}"
if [ "$OS" = "Darwin" ]; then
chmod 777 "${base_path}" "${data_path}" || true
else
chown -R 999:999 "${data_path}" 2>/dev/null || true
chmod 700 "${data_path}" 2>/dev/null || true
fi
echo "created data dir: ${data_path}"
# -------------------------
# Memory-aware minimal tuning (only safe params)
# -------------------------
total_mem_bytes="$(get_total_mem_bytes)"
if [ "${total_mem_bytes}" -le 0 ]; then
total_mem_bytes=$((4 * 1024 * 1024 * 1024)) # fallback 4GB
fi
total_mem_mb="$(bytes_to_mb "$total_mem_bytes")"
total_mem_gb="$(bytes_to_gb "$total_mem_bytes")"
# shared_buffers ~25% RAM
shared_buffers_mb=$(( total_mem_mb / 4 ))
[ "$shared_buffers_mb" -lt 128 ] && shared_buffers_mb=128
# effective_cache_size ~75% RAM
effective_cache_mb=$(( total_mem_mb * 3 / 4 ))
[ "$effective_cache_mb" -lt 512 ] && effective_cache_mb=512
# maintenance_work_mem ~5% RAM, with caps
maintenance_mb=$(( total_mem_mb / 20 ))
[ "$maintenance_mb" -lt 64 ] && maintenance_mb=64
[ "$maintenance_mb" -gt 2048 ] && maintenance_mb=2048
# conservative work_mem
work_mem_mb=$(( total_mem_mb / 100 / 10 ))
[ "$work_mem_mb" -lt 4 ] && work_mem_mb=4
[ "$work_mem_mb" -gt 64 ] && work_mem_mb=64
max_connections=100
echo "Host RAM detected: ~${total_mem_gb} GB (${total_mem_mb} MB)"
echo "Tuning:"
echo " shared_buffers = ${shared_buffers_mb}MB"
echo " effective_cache_size = ${effective_cache_mb}MB"
echo " maintenance_work_mem = ${maintenance_mb}MB"
echo " work_mem = ${work_mem_mb}MB"
echo " max_connections = ${max_connections}"
# -------------------------
# Run container
# -------------------------
if docker ps -a --format '{{.Names}}' | grep -q "^${docker_servicename}$"; then
echo "Container ${docker_servicename} already exists. Removing..."
docker rm -f "${docker_servicename}" >/dev/null
fi
publish_spec="${bind_ip}:${docker_port}:5432"
echo
echo "Starting container:"
echo " name = ${docker_servicename}"
echo " image = postgres:${docker_pgversion}"
echo " bind = ${publish_spec}"
echo " data = ${data_path}"
docker run --restart unless-stopped -d \
--name "${docker_servicename}" \
-e POSTGRES_USER="${docker_superuser}" \
-e POSTGRES_PASSWORD="${docker_pass}" \
-v "${data_path}:/var/lib/postgresql/data" \
-p "${publish_spec}" \
"postgres:${docker_pgversion}" \
postgres \
-c "shared_buffers=${shared_buffers_mb}MB" \
-c "effective_cache_size=${effective_cache_mb}MB" \
-c "maintenance_work_mem=${maintenance_mb}MB" \
-c "work_mem=${work_mem_mb}MB" \
-c "max_connections=${max_connections}"
# -------------------------
# ~/.pgpass
# -------------------------
target_home="$(detect_target_home)"
pgpass_file="${target_home}/.pgpass"
mkdir -p "${target_home}"
touch "${pgpass_file}"
# If bound to 0.0.0.0, local client still uses 127.0.0.1
pgpass_host="127.0.0.1"
if [ "$bind_ip" != "0.0.0.0" ]; then
pgpass_host="$bind_ip"
fi
pgpass_line="${pgpass_host}:${docker_port}:*:${docker_superuser}:${docker_pass}"
grep -qxF "${pgpass_line}" "${pgpass_file}" 2>/dev/null || echo "${pgpass_line}" >> "${pgpass_file}"
chmod 600 "${pgpass_file}" 2>/dev/null || true
if [ -n "${SUDO_USER:-}" ] && [ "$OS" != "Darwin" ]; then
chown "${SUDO_USER}:${SUDO_USER}" "${pgpass_file}" 2>/dev/null || true
fi
# -------------------------
# Optional BACKUP
# -------------------------
echo
echo "Enable daily backup via cron? (y/N): "
read -r enable_backup
enable_backup="${enable_backup:-N}"
backup_script_path=""
backup_dir_base="/backup"
backup_host="$(hostname -s 2>/dev/null || hostname)"
retention_days=15
cron_hour=2
cron_minute=30
cron_status="disabled"
if [[ "${enable_backup}" =~ ^[Yy]$ ]]; then
backup_script_path="/usr/local/bin/${docker_servicename}-backup"
mkdir -p "${backup_dir_base}/${backup_host}"
cat > "${backup_script_path}" <<EOF
#!/bin/bash
set -euo pipefail
# Auto-generated backup script for ${docker_servicename}
# You can edit this file safely.
CONTAINER_NAME="${docker_servicename}"
PGUSER="${docker_superuser}"
BACKUP_BASE="${backup_dir_base}"
HOSTNAME_STR="\$(hostname -s 2>/dev/null || hostname)"
BACKUP_DIR="\${BACKUP_BASE}/\${HOSTNAME_STR}"
RETENTION_DAYS=${retention_days}
DATE_STR="\$(date +%F_%H-%M-%S)"
OUT_FILE="\${BACKUP_DIR}/\${CONTAINER_NAME}_\${DATE_STR}.sql.gz"
mkdir -p "\${BACKUP_DIR}"
# Dump all databases and roles, gzip on host side.
docker exec -i "\${CONTAINER_NAME}" pg_dumpall -U "\${PGUSER}" | gzip -9 > "\${OUT_FILE}"
# Purge old backups for this service
find "\${BACKUP_DIR}" -type f -name "\${CONTAINER_NAME}_*.sql.gz" -mtime +\${RETENTION_DAYS} -delete
echo "Backup OK: \${OUT_FILE}"
EOF
chmod 750 "${backup_script_path}" 2>/dev/null || true
if command -v crontab >/dev/null 2>&1; then
existing_cron="$(crontab -l 2>/dev/null || true)"
cron_line="${cron_minute} ${cron_hour} * * * ${backup_script_path} >/dev/null 2>&1"
if ! echo "${existing_cron}" | grep -Fq "${backup_script_path}"; then
( echo "${existing_cron}"; echo "${cron_line}" ) | crontab -
cron_status="enabled"
else
cron_status="already-present"
fi
else
cron_status="crontab-not-found"
fi
fi
# -------------------------
# /etc/info
# -------------------------
cat <<EOF
OK - new PostgreSQL server created:
Service = ${docker_servicename}
Image = postgres:${docker_pgversion}
Host bind:
host = ${pgpass_host}
port = ${docker_port}
user = ${docker_superuser}
password = ${docker_pass} (saved to ${pgpass_file})
Paths:
data = ${data_path}
Quick connect:
psql -h ${pgpass_host} -p ${docker_port} -U ${docker_superuser}
Inside container:
docker exec -it ${docker_servicename} psql -U ${docker_superuser}
Logs:
docker logs -f ${docker_servicename}
EOF
if [[ "${enable_backup}" =~ ^[Yy]$ ]]; then
cat <<EOF
Backup:
script = ${backup_script_path}
dir = ${backup_dir_base}/${backup_host}
retention = ${retention_days} days
cron = ${cron_status} (daily at ${cron_hour}:${cron_minute})
EOF
fi
echo
echo "This information is copied to /etc/info."
{
echo "PostgreSQL server running:"
echo "service = ${docker_servicename}"
echo "image = postgres:${docker_pgversion}"
echo
echo "host = ${pgpass_host}"
echo "port = ${docker_port}"
echo "user = ${docker_superuser}"
echo "password = ${docker_pass} (saved to ${pgpass_file})"
echo
echo "data = ${data_path}"
echo
echo "connect = psql -h ${pgpass_host} -p ${docker_port} -U ${docker_superuser}"
echo "dockerpsql= docker exec -it ${docker_servicename} psql -U ${docker_superuser}"
echo "logs = docker logs -f ${docker_servicename}"
if [[ "${enable_backup}" =~ ^[Yy]$ ]]; then
echo
echo "backup:"
echo " script = ${backup_script_path}"
echo " dir = ${backup_dir_base}/${backup_host}"
echo " retention = ${retention_days} days"
echo " cron = ${cron_hour}:${cron_minute} daily"
fi
echo
} >> /etc/info
chmod 600 /etc/info 2>/dev/null || true
exit 0