Michele Carino
Michele Carino

Reputation: 1048

Docker compose and postgres official image environment variables

Actually I'm using the following docker-compose.yml file

version: '3.3'

  services:
    postgres:
      container_name: postgres
      image: postgres:latest
      restart: always
      environment:
        POSTGRES_USER: ${POSTGRES_USER}
        POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
        POSTGRES_DB: ${POSTGRES_DB}
        PGDATA: /var/lib/postgresql/data/pgdata
      ports:
        - "5432:5432"
      volumes:
        - ./data/postgres/pgdata:/var/lib/postgresql/data/pgdata

I use also this .env file in the same directory of the docker-compose.yml file:

POSTGRES_USER=dbadm
POSTGRES_PASSWORD=dbpwd
POSTGRES_DB=db

Then I run a bash shell into container this way:

docker exec -ti postgres bash

And after this invoke the command:

psql -h postgres -U dbadm db

And I get the error:

psql: FATAL:  password authentication failed for user "dbadm"

The strange fact is that if use the default image parameters:

psql -h postgres -U admin database

And insert the default password "password", it logs me in, and seems it's ignoring the environment variables.

What am I missing?

Additional logs from docker-compose up logs:

postgres    | 2017-10-15 09:19:15.502 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres    | 2017-10-15 09:19:15.502 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres    | 2017-10-15 09:19:15.505 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres    | 2017-10-15 09:19:15.524 UTC [22] LOG:  database system was shut down at 2017-10-15 09:02:21 UTC
postgres    | 2017-10-15 09:19:15.530 UTC [1] LOG:  database system is ready to accept connections

Cannot see any "RUN" line about user, database and password setup.

Upvotes: 14

Views: 58779

Answers (2)

Sergiu
Sergiu

Reputation: 3185

I have created a docker-compose yml and .env file with the details you've provided and everything works fine as you can see from the pictures below:

enter image description here enter image description here

I think your problem lies when you are passing the -h parameter.

Inside the container will always be localhost however, outside you will have to pass:

hostname: postgres

inside your docker-compose file so it will have the postgres hostname

Upvotes: 3

kris mwas
kris mwas

Reputation: 111

according to https://hub.docker.com/_/postgres documentation.

Warning: the Docker specific variables will only have an effect if you start the container with a data directory that is empty; any pre-existing database will be left untouched on container startup.

Upvotes: 11

Related Questions