1

I have the following docker-compose.yml:

version: '3.4'

services:
  # bla bla bla

  pg:
    image: postgres:9.6    
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD:
      POSTGRES_DB: just_db
volumes:
  pgdata:

And following Dockerfile:

FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /src
COPY . .
RUN dotnet publish ./src/WebApp/WebApp.csproj -c Release -o /app

FROM microsoft/dotnet:2.2-aspnetcore-runtime AS final
WORKDIR /app
EXPOSE 80
COPY --from=build /app .

ENTRYPOINT ["dotnet"]
CMD ["WebApp.dll"]

As I read if I set POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB variables in docker-compose.yml db will be created. And sql scripts from folder docker-entrypoint-initdb.d will be executed. I expect database just_db to be created after I run docker-compose up --build but it doesn't happen. How do I create database with docker-comose?

1
  • Did you check with out volume? Commented Oct 13, 2019 at 13:31

1 Answer 1

2

docker-compose will only create a database if $PGDATA doesn't already exist. This is because initdb is only called when $PGDATA is empty (or more precisely, when no PG_VERSION file exists). Please see the entrypoint source for more info. Since you are providing pgdata:/var/lib/postgresql/data in your docker-compose.yml, Docker will simply use what's already there, and won't create an additional database named just_db. If you want it to create just_db, then you will need to either provide a $PGDATA volume that is empty (or remove PG_VERSION, but that might make things even more messy), or omit the volume altogether.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.