How to build a docker image which can restore databases whenever a new container is created from it
Umesh Kumar Dhakar
Posted on August 29, 2018
1. Run a postgres container.
docker container run --name <name> --detach -p 5432:5432 -e POSTGRES_PASSWORD=<my-pass> postgres
(ex: docker container run --name store --detach -p 5432:5432 -e POSTGRES_PASSWORD=my-pass postgres)
2. Create a directory in container to copy backup file.
docker exec <container_name> mkdir /<dir_name>
(ex: docker exec store mkdir /data)
3. Copy a backup file in container from Host or from another container.
docker cp /path/of/backup_file/database_bkp.sql <container_name>:/path/to/copy/file
(ex: docker cp /volume1/database_bkp.sql store:/data)
4. Install an editor in container (nano or vim etc...).
apt-get update
apt-get install vim
export EDITOR=vim
5. Create file in /docker-entrypoint-initdb.d directory
touch /docker-entrypoint-initdb.d/<file_name>
(ex: touch /docker-entrypoint-initdb.d/restore_db.sh )
6. write restore script in restore_db.sh
#!/bin/bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" -f /data/database_bkp.sql
(if you dumped only a single database using pg_dump then please mention database name also in script)
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" -d <database-name> -f /data/database_bkp.sql)
7. Make file executable
chmod 755 /docker-entrypoint-initdb.d/restore_db.sh
8. Build a new image from running container.
docker commit <running-container> <new-image>
(ex: docker commit store store_new)
9. Verify that image has built properly.
docker image ls
10. Run container from newly build image on a different port.
docker container run --name <name> --detach -p 4432:5432 -e POSTGRES_PASSWORD=<my-pass> <new-image>
(eg: docker container run --name store_postgres --detach -p 4432:5432 -e POSTGRES_PASSWORD=my-pass store_new)
This image has a restore file in it, a database is created when a new container is created from this image
Thanks for reading! 😊, This is my first post. Please let me know if you have any issue and also please write feedback.
Posted on August 29, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.