Build postgres docker container with initial schema

前端 未结 2 2081
温柔的废话
温柔的废话 2020-12-13 00:26

I\'m looking to build dockerfiles that represent company databases that already exist. Similarly, I\'d like create a docker file that starts by restoring a psql dump.

<
2条回答
  •  被撕碎了的回忆
    2020-12-13 01:03

    As said in the comments, @Thomasleveil answer is great and simple if your schema recreation is fast. But in my case it's slow, and I wanted to use docker volumes, so here is what I did

    1. First use docker image as in @Thomasleveil answer to create a container with postgres with all the schema initialization

    Dockerfile:

    FROM postgres
    WORKDIR /docker-entrypoint-initdb.d
    ADD psql_dump.sql /docker-entrypoint-initdb.d
    EXPOSE 5432
    
    1. then run it and create new local dir which contains the postgres data after its populated from the “psql_dump.sql” file: docker cp mypg:/var/lib/postgresql/data ./postgres-data

    2. Copy the data to a temp data folder, and start a new postgres docker-compose container whose volume is at the new temp data folder:

    startPostgres.sh:

    rm -r ./temp-postgres-data/data
    mkdir -p ./temp-postgres-data/data
    cp -r ./postgres-data/data ./temp-postgres-data/
    docker-compose -p mini-postgres-project up
    

    and the docker-compose.yml file is:

    version: '3'
    services:
      postgres:
        container_name: mini-postgres
        image: postgres:9.5
        ports:
        - "5432:5432"
        volumes:
          - ./temp-postgres-data/data:/var/lib/postgresql/data
    

    Now you can run steps #1 and #2 on a new machine or if your psql_dump.sql changes. And each time you want a new clean (but already initialized) db, you can only run startPostgres.sh from step #3. And it still uses docker volumes.

提交回复
热议问题