Zacksung Zeng
Zacksung Zeng

Reputation: 81

postgres in docker container role "postgres" does not exist

  1. Create a postgres docker container with below command: docker run -v /home/ec2-user/Vteck-postgres-data:/var/lib/postgresql/data -d -e POSTGRES_USER=odoo POSTGRES_PASSWORD=odoo -e POSTGRES_DB=postgres --name vteck-db postgres

  2. access Docker container: docker exec -it vteck-db bash

  3. Connect with the client: root@f1ba565db798:/# psql -U postgres psql: error: could not connect to server: FATAL: role "postgres" does not exist

but if I create Docker container with docker run --rm -d -e POSTGRES_PASSWORD=root --name postgres postgres, I can successfully connect with psql - U postgres.

Any problem with my first step's command?

Upvotes: 8

Views: 20621

Answers (2)

anemyte
anemyte

Reputation: 20196

From postgres readme on Docker hub:

POSTGRES_USER

This optional environment variable is used in conjunction with POSTGRES_PASSWORD to set a user and its password. This variable will create the specified user with superuser power and a database with the same name. If it is not specified, then the default user of postgres will be used.

In other words if you put something into the POSTGRES_USER environment variable, the startup script will honor that and create that user instead of the default one (postgres, that is).

Also, this and other POSTGRES_* variables are only used during the initial startup, when the database directory is empty. So if you restart the container with some other value, it won't make any difference (you'll see in logs something about "database seems ok, skipping initialization") unless you manually deleted the database.

Upvotes: 16

mistige
mistige

Reputation: 667

In your yml file, make a POSTGRES_DB that is NOT 'postgres'

<snip>
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: heavymetaldifficultmoeilijk
      POSTGRES_DB: foodb
<snip>

Connect to your container from the host:

# docker exec -it myproject_pg_container_name /bin/bash

Then, from the container:

root@d14c082e80c8:/# psql -U postgres

Michael

Upvotes: 0

Related Questions