Pupkin
Pupkin

Reputation: 1091

Create database with docker-compose

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?

Upvotes: 1

Views: 1299

Answers (1)

richyen
richyen

Reputation: 9958

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.

Upvotes: 2

Related Questions