Search code examples
postgresqldockerdocker-composedocker-container

Docker compose: Error: role "hleb" does not exist


Kindly ask you to help with docker and Postgres.

  • I have a local Postgres database and a project on NestJS.

  • I killed 5432 port.

  • My Dockerfile

FROM node:16.13.1

WORKDIR /app

COPY package.json ./
COPY yarn.lock ./

RUN yarn install

COPY . .

COPY ./dist ./dist
CMD ["yarn", "start:dev"]

  • My docker-compose.yml
version: '3.0'

services:
  main:
    container_name: main
    build:
      context: .
    env_file:
      - .env
    volumes:
      - .:/app
      - /app/node_modules
    ports:
      - 4000:4000
      - 9229:9229
    command: yarn start:dev
    depends_on:
      - postgres
    restart: always

  postgres:
    container_name: postgres
    image: postgres:12
    env_file:
      - .env
    environment:
      PG_DATA: /var/lib/postgresql/data
      POSTGRES_HOST_AUTH_METHOD: 'trust'
    ports:
      - 5432:5432
    volumes:
      - pgdata:/var/lib/postgresql/data
    restart: always

volumes:
  pgdata:

  • .env
DB_TYPE=postgres
DB_HOST=postgres
DB_PORT=5432
DB_USERNAME=hleb
DB_NAME=artwine
DB_PASSWORD=Mypassword

  • running sudo docker-compose build - NO ERRORS

  • running sudo docker-compose up --force-recreate - ERROR

ERROR [ExceptionHandler] role "hleb" does not exist.

I've tried multiple suggestions from existing issues but nothing helped. What am I doing wrong? Thanks!


Solution

    • Do not use sudo - unless you have to.
    • Use the latest Postgres release if possible.

    The Postgresql Docker Image provides some environment variables, that will help you bootstrapping your database.

    Be aware:

    The PostgreSQL image uses several environment variables which are easy to miss. The only variable required is POSTGRES_PASSWORD, the rest are optional.

    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.

    When you do not provide the POSTGRES_USER environment variable in the docker-compose.yml file, it will default to postgres.

    Your .env file used for Docker Compose does not contain the docker specific environment variables.

    So amending/extending it to:

    POSTGRES_USER=hleb
    POSTGRES_DB=artwine
    POSTGRES_PASSWORD=Mypassword
    

    should do the trick. You will have to re-create the volume (delete it) to make this work, if the data directory already exists.