#!/bin/sh set -eu PGDATA=${PGDATA:-/data/postgres} DB_NAME=${DB_POSTGRESDB_DATABASE:-n8n} DB_USER=${DB_POSTGRESDB_USER:-n8n} DB_PASS=${DB_POSTGRESDB_PASSWORD:-} echo "[postgres] PGDATA=$PGDATA" if [ ! -f "$PGDATA/PG_VERSION" ]; then echo "[postgres] PGDATA missing, waiting for entrypoint init..." # wait max 60s for init for i in $(seq 1 60); do [ -f "$PGDATA/PG_VERSION" ] && break sleep 1 done fi # Start postgres as postgres user via su-exec echo "[postgres] starting" # Ensure ownership chown postgres:postgres "$PGDATA" 2>/dev/null || true # Use su-exec to run postgres; postgres writes pid to PGDATA/postmaster.pid exec su-exec postgres postgres -D "$PGDATA" -c listen_addresses=127.0.0.1 -c port=5432 & PGPID=$! # Wait for ready, then create db/user if needed for i in $(seq 1 60); do if su-exec postgres pg_isready -h 127.0.0.1 -p 5432 >/dev/null 2>&1; then echo "[postgres] ready" break fi sleep 1 done # Create user/db if not exists if su-exec postgres pg_isready -h 127.0.0.1 -p 5432 >/dev/null 2>&1; then if ! su-exec postgres psql -h 127.0.0.1 -U postgres -tc "SELECT 1 FROM pg_roles WHERE rolname='$DB_USER'" | grep -q 1; then echo "[postgres] creating user $DB_USER" su-exec postgres psql -h 127.0.0.1 -U postgres -v ON_ERROR_STOP=1 </dev/null 2>&1 || true fi # Wait on postgres pid wait $PGPID