@@ -39,10 +39,19 @@ if [ "$1" = 'postgres' ] && [ -z "$(ls -A "$PGDATA" 2>/dev/null)" ]; then
3939
4040 # Create additional user/database if specified
4141 if [ -n " $POSTGRES_DB " ] || [ -n " $POSTGRES_USER " ]; then
42+ # Temporarily allow local connections without password for setup
43+ HBA_BACKUP=" $PGDATA /pg_hba.conf.backup"
44+ cp " $PGDATA /pg_hba.conf" " $HBA_BACKUP "
45+ echo " local all all trust" > " $PGDATA /pg_hba.conf"
46+ echo " host all all all trust" >> " $PGDATA /pg_hba.conf"
47+
4248 pg_ctl -D " $PGDATA " -o " -c listen_addresses=''" -w start
4349
50+ # Connect to the postgres database (which always exists) for running SQL commands
51+ PSQL_CMD=" psql -v ON_ERROR_STOP=1 --username ${POSTGRES_USER:- postgres} --dbname postgres"
52+
4453 if [ " $POSTGRES_DB " != ' postgres' ] && [ -n " $POSTGRES_DB " ]; then
45- psql -v ON_ERROR_STOP=1 --username " ${POSTGRES_USER :- postgres} " << -EOSQL
54+ $PSQL_CMD << -EOSQL
4655 CREATE DATABASE "$POSTGRES_DB ";
4756EOSQL
4857 fi
@@ -51,12 +60,15 @@ EOSQL
5160 for f in /docker-entrypoint-initdb.d/* ; do
5261 case " $f " in
5362 * .sh) echo " Running $f " ; . " $f " ;;
54- * .sql) echo " Running $f " ; psql -v ON_ERROR_STOP=1 --username " ${POSTGRES_USER :- postgres} " -f " $f " ;;
63+ * .sql) echo " Running $f " ; $PSQL_CMD -f " $f " ;;
5564 * ) echo " Ignoring $f " ;;
5665 esac
5766 done 2> /dev/null || true
5867
5968 pg_ctl -D " $PGDATA " -m fast -w stop
69+
70+ # Restore original pg_hba.conf with proper authentication
71+ mv " $HBA_BACKUP " " $PGDATA /pg_hba.conf"
6072 fi
6173
6274 echo " PostgreSQL init complete; ready for start up."
0 commit comments