Search code examples
postgresqldockerdocker-compose

"FATAL: role " postgres" does not exist" When running postgres docker image


I'm working on a app where I use a postgres database. I run everything in containers using docker-compose.

My compose file looks like this:

version: '3.8'

services:
  backend:
    ... # Backend stuff, runs fine
    depends_on:
      - db
  frontend:
    ... #Frontend stuff, runs fine
  db:
    image: postgres
    volumes:
      - ./db/data:/var/lib/postgresql/data
    ports:
      - 5432:5432
    environment:
      - POSTGRES_PASSWORD=*********** #This is a proper password
    healthcheck:
      test: ["CMD","pg_isready", "-d", "postgres", "-h", "localhost", "-p 5432", "-U postgres"]
      interval: 10s
      timeout: 30s
      retries: 5
      start_period: 30s

Everything works and runs fine, however, my database container constantly prints out this error message:

FATAL: role " postgres" does not exist

I do not specify any users, so from my understanding the default role "postgres" should be created when building the image.

I have also seen many people experiencing this problem if they have other postgres databases running on their system, this is not the case for me.

PS.

My backend is written in python using FastAPI and SQLAlchemy with psycopg. And it connects to the database using the URL 'postgresql+psycopg://postgres:DBPASSWORD@db:5432'


Solution

    • Docker networking might not resolve localhost to the correct container IP. For that case, remove localhost and add db. With this change, -h db tells PostgreSQL to connect to the service named db defined in your compose file.
    version: '3.8'
    
    services:
      backend:
        ... # Backend stuff, runs fine
        depends_on:
          - db
      frontend:
        ... #Frontend stuff, runs fine
      db:
        image: postgres
        volumes:
          - ./db/data:/var/lib/postgresql/data     
        ports:
          - 5432:5432
        environment:
          - POSTGRES_PASSWORD=*********** #This is a proper password
        healthcheck:
          test: 
            [
              "CMD",
              "pg_isready",
              "-d",
              "postgres",
              "-h",
              "db", # Changed "localhost" to "db"
              "-p 5432",
              "-U postgres",
            ]
          interval: 10s
          timeout: 30s
          retries: 5
          start_period: 30s
    volumes:
      db-data: