Backing up Docker Containers

Photo by Justus Menke on Unsplash

In my setup, I do use bind mounts for my volumes.

volumes
├── blog
├── blogdb
├── etherdb
└── pihole

So in order to be able to backup e.g. my databases, I need to stop the running docker containers. How to do that:

CONTAINERS=`docker ps -aq`

to store all the IDs of running containers in a shell variable.
Then you can issue

docker stop $CONTAINERS

to stop all containers running at the point in time when you stored the containers in the $CONTAINERS variable.
I make this explicit, as in environments with lots of stopping and starting of containers between writing to
and reading from the variable the system’s state might have been modified.

Then you can do you backup stuff, in my case:

#! /bin/bash
DATE=`date +%d-%m-%Y`
DOCKER_BASE_DIR=/home/hasgarion/docker
BACKUP_BASE_DIR=/home/hasgarion/backups
FILENAME=$BACKUP_BASE_DIR/docker-$DATE.tgz
DESTINATION="hasgarion@megastore:~/backups"

function startContainer {
docker start $CONTAINERS
}


echo "Collecting running containers"
CONTAINERS=`docker ps -aq`

echo "Stopping containers"
docker stop $CONTAINERS
if [ $? -ne 0 ]; then
echo "Stopping docker containers failed"
echo "Trying to restart containers"
starContainer
exit 1
else
echo "Succeeded"
fi




echo "Checking if backups dir $BACKUP_BASE_DIR exists"
if [ -d "$BACKUP_BASE_DIR" ]; then
echo "Success"
else
echo "Error, $BACKUP_BASE_DIR does not exist"
startContainer
exit 1
fi

echo "Checking if docker dir $DOCKER_BASE_DIR exists"
if [ -d "$DOCKER_BASE_DIR" ]; then
echo "Success"
else
echo "Error, $DOCKER_BASE_DIR does not exist"
startContainer
exit 1
fi

echo "About to create $FILENAME from $DOCKER_BASE_DIR"
tar -czf $FILENAME $DOCKER_BASE_DIR
if [ $? -ne 0 ]; then
echo "TAR command failed"
startContainer
exit 1
else
echo "Succeeded"
fi

echo "About to copy the backup file to the remote"
scp -q $FILENAME $DESTINATION
if [ $? -ne 0 ]; then
echo "SCP command failed"
startContainer
exit 1
else
echo "Succeeded"
fi

startContainer
exit 0

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.