Build Docker Image Postgres With Data Included

NK
NK
Jul 16, 2018 · 1 min read

In docker images of databases, data is stored in volumes. A directory of host machine is mounted as volume. This way when container stops or gets killed, data is not lost. It can always be present in that mounted directory.

But for use cases where you want to have a database snapshot including configuration and data, docker does not provide a proper solution.

What we can do is.

docker run — name ps-export -p 5431:5432 -i postgres

This command will create a postgres container named ps-export running at mentioned port.

Postgres data resides by-default in directory /var/lib/postgresql/data

Data is not exactly in this directory, A host directory is mounted via volumes to this directory.

Anyways, now copy the data from this directory to another directory

mkdir /postgres
cp -r /var/lib/postgresql/data/* /postgres

Now this data is part of this container. Commit this container to an image

docker commit ps-export ps_image_with_data

pg_export is a postgres image with data as well. You can push this image to docker hub as well to make it available publicly.

docker run — env PGDATA=postgres -p 5433:5432 -i ps_image_with_data

This command will start postgres container at port 5433 where data directory is /postgres.

THAT’S IT.

NK

Written by

NK

Engineer at Grofers

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade