1

I want to create a database after starting the Postgres Docker image.

The problem is if I put my database creation command in my docker-compose file or a child dockerfile it overrides the base image's command to actually start postgres - so my psql has no started server to connect to.

E.g.:

version: '2'
services:
  db:
    command: bash -c "su - postgres -c '/usr/lib/postgresql/9.6/bin/psql  -h 127.0.0.1 -p 6543 -U postgres -c \"create database dev;\"'"
    environment:
      - PGDATA=/pg
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_USER=postgres
    image: postgres:9.6
    ports:
      - '6543:5432'
    tmpfs: /pg

And the image documentation doesn't say the exact command they are running to start Postgres. I tried putting bash -c "postgres && ... at the beginning of my command but it fails telling me I can't start Postgres as root.

The only possible solution I can find is to abandon docker-compose and dockerfile in favour of a bash script solution, like docker run postgres:9.6 psql -h postgres -U postgres -c 'create database' but this is horrible.

What to do?

Richard
  • 14,798
  • 21
  • 70
  • 103

1 Answers1

5

I would not do it this way. Why not start a second container with the desired DB name?

environment:
  - PGDATA=/pg
  - POSTGRES_PASSWORD=postgres
  - POSTGRES_USER=postgres
  - POSTGRES_DB=dev

Just run a container for every database.. would prefer this as clean solution.

opHASnoNAME
  • 20,224
  • 26
  • 98
  • 143