1+ #! /bin/sh
2+ set -e
3+
4+ # Run as postgres user if started as root
5+ if [ " $( id -u) " = ' 0' ]; then
6+ exec su-exec postgres " $0 " " $@ "
7+ fi
8+
9+ # Initialize database if PGDATA is empty
10+ if [ " $1 " = ' postgres' ] && [ -z " $( ls -A " $PGDATA " 2> /dev/null) " ]; then
11+ # Set password file for initdb
12+ if [ -n " $POSTGRES_PASSWORD " ]; then
13+ PWFILE=$( mktemp)
14+ printf ' %s' " $POSTGRES_PASSWORD " > " $PWFILE "
15+ INITDB_OPTS=" --pwfile=$PWFILE "
16+ AUTH_METHOD=" scram-sha-256"
17+ elif [ " ${POSTGRES_HOST_AUTH_METHOD:- } " = ' trust' ]; then
18+ AUTH_METHOD=" trust"
19+ INITDB_OPTS=" "
20+ else
21+ echo " Error: POSTGRES_PASSWORD must be set or POSTGRES_HOST_AUTH_METHOD=trust" >&2
22+ exit 1
23+ fi
24+
25+ initdb \
26+ --username=" ${POSTGRES_USER:- postgres} " \
27+ --auth-host=" $AUTH_METHOD " \
28+ --auth-local=" $AUTH_METHOD " \
29+ $INITDB_OPTS \
30+ " $PGDATA "
31+
32+ [ -n " ${PWFILE:- } " ] && rm -f " $PWFILE "
33+
34+ # Configure listening
35+ echo " listen_addresses = '*'" >> " $PGDATA /postgresql.conf"
36+
37+ # Allow connections from anywhere (container networking)
38+ echo " host all all all $AUTH_METHOD " >> " $PGDATA /pg_hba.conf"
39+
40+ # Create additional user/database if specified
41+ if [ -n " $POSTGRES_DB " ] || [ -n " $POSTGRES_USER " ]; then
42+ pg_ctl -D " $PGDATA " -o " -c listen_addresses=''" -w start
43+
44+ if [ " $POSTGRES_DB " != ' postgres' ] && [ -n " $POSTGRES_DB " ]; then
45+ psql -v ON_ERROR_STOP=1 --username " ${POSTGRES_USER:- postgres} " << -EOSQL
46+ CREATE DATABASE "$POSTGRES_DB ";
47+ EOSQL
48+ fi
49+
50+ # Run init scripts if present
51+ for f in /docker-entrypoint-initdb.d/* ; do
52+ case " $f " in
53+ * .sh) echo " Running $f " ; . " $f " ;;
54+ * .sql) echo " Running $f " ; psql -v ON_ERROR_STOP=1 --username " ${POSTGRES_USER:- postgres} " -f " $f " ;;
55+ * ) echo " Ignoring $f " ;;
56+ esac
57+ done 2> /dev/null || true
58+
59+ pg_ctl -D " $PGDATA " -m fast -w stop
60+ fi
61+
62+ echo " PostgreSQL init complete; ready for start up."
63+ fi
64+
65+ exec " $@ "
0 commit comments