Search code examples
postgresqldockerdocker-compose

Running Docker Compose in Visual Studio Throws Postgres Uninitialized Error


I added Docker orchestration to a .NET 8 Web API and in the docker-compose.yml, I added services for the Postgres image and API project as such:

services:
  bookify.api:
    image: ${DOCKER_REGISTRY-}bookifyapi
    build:
      context: .
      dockerfile: Bookify.Api/Dockerfile
    depends_on:
      - bookify-db
  
  bookify-db:
    image: 'postgres:latest'
    container_name: Bookify.Db
    environment:
      - POSTGRES_DB= bookify
      - POSTGRES_USER = postgres 
      - POSTGRES_PASSWORD = postgres 
    volumes:
      - ./.containers/database:/var/lib/postgresql/data
    ports:
      - 5432:5432

When I run Docker Compose in Visual Studio (or try to run the images in Docker Desktop) the API image runs, but the database image throws the following error:

Database is uninitialized and superuser password is not specified.
You must specify POSTGRES_PASSWORD to a non-empty value for the
superuser. For example, "-e POSTGRES_PASSWORD=password" on "docker run".

I've found quite a few answers on SO and microsoft mentioning to just add the environment variable for POSTGRES_PASSWORD, but I have that already in the docker-compose.yml file.

Here is the docker run command that is generated from running Docker Compose:

docker run --hostname=ee75d8072999 --env=POSTGRES_USER = postgres --env=POSTGRES_PASSWORD = postgres --env=POSTGRES_DB= bookify --env=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/postgresql/16/bin --env=GOSU_VERSION=1.17 --env=LANG=en_US.utf8 --env=PG_MAJOR=16 --env=PG_VERSION=16.4-1.pgdg120+1 --env=PGDATA=/var/lib/postgresql/data --' --runtime=runc -d postgres:latest

I'm not sure what I'm missing. Do I need to create a database with that name, say in pgAdmin, or is there something I'm missing that also needs to be downloaded?


Solution

  • You should define your environment variables without whitespaces:

    environment:
      - POSTGRES_DB=bookify
      - POSTGRES_USER=postgres 
      - POSTGRES_PASSWORD=postgres