File size: 1,873 Bytes
4c98a98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/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