docker-library / postgres

Docker Official Image packaging for Postgres
http://www.postgresql.org
MIT License
2.14k stars 1.11k forks source link

Add new "docker-ensure-initdb.sh" script #1150

Closed tianon closed 7 months ago

tianon commented 7 months ago

This mimics the behavior of docker-entrypoint.sh before it starts the PostgreSQL server.

It has three main goals/uses:

  1. (most importantly) as an example of how to use "docker-entrypoint.sh" to extend/reuse the initialization behavior

  2. ("docker-ensure-initdb.sh") as a Kubernetes "init container" to ensure the provided database directory is initialized; see also "startup probes" for an alternative solution (no-op if database is already initialized)

  3. ("docker-enforce-initdb.sh") as part of CI to ensure the database is fully initialized before use (error if database is already initialized)

Closes #1141 (alternative to) Closes #1113 Closes #731

This is something I wrote more than a year ago, but wasn't sure we wanted to actually commit to maintaining over time (and I'm still not 100% sold, but it does seem useful as an example of how to use docker-entrypoint.sh correctly).

LaurentGoderre commented 7 months ago

Im probably using this wrong but it gives me:

/usr/local/bin/docker-ensure-initdb.sh: line 34: DATABASE_ALREADY_EXISTS: unbound variable

I think that's because that variable is defined inside a function in the entrypoint.

LaurentGoderre commented 7 months ago

Beside the minor code issue, I confirm this meets the use case in #1141 using:

services:
  db-init:
    build:
      context: ../alpine3.18
    image: postgres:16-alpine
    environment:
      POSTGRES_PASSWORD: example
    volumes:
      - pgdata:/var/lib/postgresql/data/
    user: postgres
    command: docker-ensure-initdb.sh
tianon commented 7 months ago

(rebased for merge conflicts)