Skip to content

Commit fbb933e

Browse files
Update init_db to skip Docker when running
1 parent 00f20c3 commit fbb933e

File tree

1 file changed

+40
-19
lines changed

1 file changed

+40
-19
lines changed

scripts/init_db.sh

Lines changed: 40 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -16,25 +16,46 @@ fi
1616
# The rest of the script
1717
set -x
1818
set -eo pipefail
19-
# Check if a custom user has been set, otherwise default to 'postgres'
20-
DB_USER="${POSTGRES_USER:=postgres}"
21-
# Check if a custom password has been set, otherwise default to 'password'
22-
DB_PASSWORD="${POSTGRES_PASSWORD:=welcome}"
23-
# Check if a custom database name has been set, otherwise default to 'newsletter'
24-
DB_NAME="${POSTGRES_DB:=zkcats}"
25-
# Check if a custom port has been set, otherwise default to '5432'
26-
DB_PORT="${POSTGRES_PORT:=5432}"
27-
# Check if a custom host has been set, otherwise default to 'localhost'
28-
DB_HOST="${POSTGRES_HOST:=localhost}"
29-
# Launch postgres using Docker
30-
docker run \
31-
-e POSTGRES_USER=${DB_USER} \
32-
-e POSTGRES_PASSWORD=${DB_PASSWORD} \
33-
-e POSTGRES_DB=${DB_NAME} \
34-
-p "${DB_PORT}":5432 \
35-
-d postgres \
36-
postgres -N 1000
37-
# ^ Increased maximum number of connections for testing purposes
19+
20+
DB_PORT="${DB_PORT:=5432}"
21+
SUPERUSER="${SUPERUSER:=postgres}"
22+
SUPERUSER_PWD="${SUPERUSER_PWD:=welcome}"
23+
APP_USER="${APP_USER:=app}"
24+
APP_USER_PWD="${APP_USER_PWD:=secret}"
25+
APP_DB_NAME="${APP_DB_NAME:=zkcats}"
26+
27+
# Allow to skip Docker if a dockerized Postgres database is already running
28+
if [[ -z "${SKIP_DOCKER}" ]]
29+
then
30+
# if a postgres container is running, print instructions to kill it and exit
31+
RUNNING_POSTGRES_CONTAINER=$(docker ps --filter 'name=postgres' --format '{{.ID}}')
32+
if [[ -n $RUNNING_POSTGRES_CONTAINER ]]; then
33+
echo >&2 "there is a postgres container already running, kill it with"
34+
echo >&2 " docker kill ${RUNNING_POSTGRES_CONTAINER}"
35+
exit 1
36+
fi
37+
CONTAINER_NAME="postgres_$(date '+%s')"
38+
# Launch postgres using Docker
39+
docker run \
40+
--env POSTGRES_USER=${SUPERUSER} \
41+
--env POSTGRES_PASSWORD=${SUPERUSER_PWD} \
42+
--health-cmd="pg_isready -U ${SUPERUSER} || exit 1" \
43+
--health-interval=1s \
44+
--health-timeout=5s \
45+
--health-retries=5 \
46+
--publish "${DB_PORT}":5432 \
47+
--detach \
48+
--name "${CONTAINER_NAME}" \
49+
postgres -N 1000
50+
# ^ Increased maximum number of connections for testing purposes
51+
52+
until [ \
53+
"$(docker inspect -f "{{.State.Health.Status}}" ${CONTAINER_NAME})" == \
54+
"healthy" \
55+
]; do
56+
>&2 echo "Postgres is still unavailable - sleeping"
57+
sleep 1
58+
done
3859

3960
# Keep pinging Postgres until it's ready to accept commands
4061
export PGPASSWORD="${DB_PASSWORD}"

0 commit comments

Comments
 (0)