DEV Community

Umesh Kumar Dhakar
Umesh Kumar Dhakar

Posted on • Edited on

How to build a docker image which can restore databases whenever a new container is created from it

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.

Top comments (2)

Collapse
 
dmfay profile image
Dian Fay

Adding the backup file to the image means that you have to rebuild the image whenever it changes. Mounting a directory from the host system as a volume would be more efficient. You might have to write a proper Dockerfile to do that though, I've never created images from running containers.

Collapse
 
umeshdhakar profile image
Umesh Kumar Dhakar

Hi Dian,

Thanks for your feedback.

You are correct, but I think building a final image can be helpful when database development is completed and then we can push it to the docker-hub, so that anyone pulls that image can have a preset database.

Please let me know if any better option is out there.

Thanks :)