3

The docs for the postgres Docker image explain that you can make the image create a user and database on creation, using environment variables.

I can't seem to make that work using docker-compose:

# docker-compose.yml
services:
  postgresql:
    image: postgres:alpine
    environment:
      POSTGRES_DB: iotplatform
      POSTGRES_USER: iotplatform
      POSTGRES_PASSWORD: iotplatform

and here's what I run:

docker-compose up -d --force-recreate postgresql
docker-compose exec postgresql psql -U iotplatform
# psql: FATAL:  role "iotplatform" does not exist

When I run docker-compose exec postgresql env, I see the environment variables as configured.

The logs don't say anything particular:

Attaching to iot-container-tracker_postgresql_1
postgresql_1  | 2018-12-17 17:35:05.754 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgresql_1  | 2018-12-17 17:35:05.754 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgresql_1  | 2018-12-17 17:35:05.757 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgresql_1  | 2018-12-17 17:35:05.770 UTC [21] LOG:  database system was shut down at 2018-12-17 17:35:03 UTC
postgresql_1  | 2018-12-17 17:35:05.772 UTC [1] LOG:  database system is ready to accept connections
postgresql_1  | 2018-12-17 17:35:22.639 UTC [34] FATAL:  role "iotplatform" does not exist

EDIT: tried without docker-compose and it works.

docker run --name some-postgres -e POSTGRES_PASSWORD=iotplatform -e POSTGRES_DB=iotplatform -e POSTGRES_USER=iotplatform -d postgres:alpine
docker exec -it some-postgres psql -U iotplatform
iotplatform=#

What am I missing?

3
  • Note that there might be some caching involved, as I first ran the image without any configuration. Is there a harder reset than --force-recreate that I should try? Commented Dec 17, 2018 at 17:46
  • Hi, I used your docker-compose part and it works well. Which version do you have of docker-compose? Commented Dec 17, 2018 at 18:20
  • @StéphaneJeandeaux docker-compose version 1.23.2, build 1110ad01 Commented Dec 18, 2018 at 8:31

2 Answers 2

3

After running down and up it works. Apparently --force-recreate wasn't a hard enough reset.

Thanks @StéphaneJeandeaux for your help.

Sign up to request clarification or add additional context in comments.

Comments

0

I suspect you created your postgres DB before assigning your POSTGRES_USER variable meaning the database first got created with the default user ('postgres').

To check if this is the case, when you run docker-compose up you will see in the logs something like:

PostgreSQL Database directory appears to contain a database; Skipping initialization

So what you need to do in this instance is remove the volume attached to the container.

i.e.

docker-compose down --volumes

or docker volume rm {volume_name}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.