n8n / scripts /run-postgres.sh
subham
Sync local n8n deployment: refactor to single Dockerfile, add runners, sandbox, cleanup legacy compose/nginx
4c98a98
Raw History Blame Contribute Delete
1.87 kB
#!/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 <<SQL
CREATE USER "$DB_USER" WITH PASSWORD '$DB_PASS';
ALTER USER "$DB_USER" CREATEDB;
SQL
fi
if ! su-exec postgres psql -h 127.0.0.1 -U postgres -lqt | cut -d \| -f 1 | grep -qw "$DB_NAME"; then
echo "[postgres] creating database $DB_NAME owner $DB_USER"
su-exec postgres createdb -h 127.0.0.1 -U postgres -O "$DB_USER" "$DB_NAME" || true
fi
# also ensure postgres user can connect
su-exec postgres psql -h 127.0.0.1 -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE \"$DB_NAME\" TO \"$DB_USER\"" >/dev/null 2>&1 || true
fi
# Wait on postgres pid
wait $PGPID