docker-library / postgres

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

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

Closed tianon closed 11 months ago

tianon commented 12 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, per https://github.com/docker-library/postgres/pull/496).

LaurentGoderre commented 12 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 12 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 11 months ago

(rebased for merge conflicts)