postgresqldockerdocker-compose

docker compose psql: error: FATAL: role "postgres" does not exist


I faced a problem when I try to use psql command with my docker-compose file on my local Ubuntu machine: psql: error: FATAL: role "postgres" does not exist

I tried to use others solution like removing docker image, volume. psql -U postgres doesn't work for me either.

I try to use first docker-compose up, then docker exec -it database bash

There's my docker-compose file

services:
  db:
    container_name: postgres
    image: postgres:13.3-alpine
    restart: always
    user: postgres
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_USER=root
    ports:
      - "5432:5432"
    volumes:
      - ./data/db:/var/lib/postgresql/data

Maybe this string tells something? postgres | PostgreSQL Database directory appears to contain a database; Skipping initialization

OUTPUT:

Attaching to postgres
postgres | 
postgres | PostgreSQL Database directory appears to contain a database; Skipping initialization
postgres | 
postgres | 2021-08-02 17:29:10.426 UTC [1] LOG:  starting PostgreSQL 13.3 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.3.1_git20210424) 10.3.1 20210424, 64-bit
postgres | 2021-08-02 17:29:10.426 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres | 2021-08-02 17:29:10.426 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres | 2021-08-02 17:29:10.429 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres | 2021-08-02 17:29:10.433 UTC [12] LOG:  database system was shut down at 2021-08-02 17:22:17 UTC
postgres | 2021-08-02 17:29:10.438 UTC [1] LOG:  database system is ready to accept connections
postgres | 2021-08-02 17:37:53.452 UTC [33] FATAL:  role "postgres" does not exist
postgres | 2021-08-02 17:37:56.958 UTC [35] FATAL:  role "user" does not exist
postgres | 2021-08-02 17:41:54.294 UTC [45] FATAL:  role "postgres" does not exist```

Solution

  • First, you've set POSTGRES_USER to root, so you're going to have a root user instead of postgres user.

    Second, if a database already exists, it doesn't matter what you set for POSTGRES_USER and POSTGRES_PASSWORD -- postgres will use whatever is in the database.

    So you can either:

    1. Delete the database (rm -rf data/db) and start over, or
    2. Edit your pg_hba.conf so that you don't need a password