theSemenov
theSemenov

Reputation: 477

How to copy and use existing postgres data folder into docker postgres container

I want to build postgres docker container for testing some issue. I have:

  1. Archived folder of postgres files(/var/lib/postgres/data/)

  2. Dockerfile that place folder into doccker postgres:latest.

I want:

  1. Docker image that reset self-state after recreate image.

  2. Container that have database state based on passed into the container postgres files

  3. I don't want to wait for a long time operation of backup and restore existing database in /docker-entrypoint-initdb.d initialization script.

  4. I DON'T WANT TO USE VOLUMES because I don't need to store new data between restart (That's why this post is different from How to use a PostgreSQL container with existing data?. In that post volumes are used)

My suggestion is to copy postgres files(/var/lib/postgres/data/) from host machine into docker's /var/lib/postgres/data/ in build phase.

But postgres docker replace this files when initdb phase is executing.

How to ask Postgres docker not overriding database files?

e.g. Dockerfile

FROM postgres:latest


COPY ./postgres-data.tar.gz /opt/pg-data/
WORKDIR /opt/pg-data
RUN tar -xzf postgres-data.tar.gz
RUN mv ./data/ /var/lib/postgresql/data/pg-data/

Run command

docker run -p 5432:5432 -e PGDATA=/var/lib/postgresql/data/pg-data --name database-immage1 database-docker

Upvotes: 5

Views: 11613

Answers (1)

b0gusb
b0gusb

Reputation: 4731

If you don't really need to create a custom image with the database snapshot you could use volumes. Un-tar the database files somewhere on the host say ~/pgdata then run the image. Example:

docker run -v ~/pgdata:/var/lib/postgresql/data/ -p 5432:5432 postgres:9.5

The files must be compatible with the postgres version of the image so use the same image version as the archived database.

If, instead, you must recreate the image you don't need to uncompress the database archive. The ADD instruction will do that for you. Make sure the tar does not contain any leading directory.

The Dockerfile:

FROM postgres:latest
ADD ./postgres-data.tar.gz /var/lib/postgresql/data/

Build it:

docker build . -t database-docker

Run without overriding the environment variable PGDATA. Note that you copy the files in /var/lib/postgresql/data but the PGDATA points to /var/lib/postgresql/data/pg-data.

Run the container:

docker run -p 5432:5432 --name  database-image1 database-docker

Upvotes: 6

Related Questions