Backup your Docker containers, the lazy way

Ever wanted to save a snapshot of all your Docker containers but never had the time or even the energy to write a script that can do that for you? Don’t worry, we are here for that reason.

Let’s just say you save these snapshots under the /backup directory of your system. Then you just will run this magic one-liner:

for CONTAINER in $(docker ps -a --format '{{.Names}}'); do
    docker export $(docker ps -a |grep $CONTAINER \
    |awk '{print $1}') > /backup/backup_${CONTAINER}_$(date +%d-%m-%Y).tar

This will save the container’s current filesystem as a tarball.

However, remember that the docker export command DOES NOT include a copy of the contents of the volumes associated to the containers, as you can read in the official Docker documentation. For that purpose you will have to mess around with another kind of solutions such as file synchronization directly over the directories linked to the volumes or so.

Also, because of how it works, the docker export command will remove the entrypoint and the container’s history, making it useful only if you want to access the container’s information, but not if you look for running the image as a container again. The way you would access to it is first creating a new image from the tarball:

docker import /backup/backup_${CONTAINER}_$(date +%d-%m-%Y).tar ${IMAGE_NAME}

And then running a container based on the new image, like this:

docker run -ti ${IMAGE_ID} /bin/bash

If you are seeking to save a copy of a existing container keeping its information as it is, you would have to use the commit function in order to generate a new image based on the current container, like this:

docker commit ${CONTAINER} ${IMAGE_NAME}_$(date +%d-%m-%Y)

Then you can export it to a new tarball:

docker save > /backup/${IMAGE_NAME}_$(date +%d-%m-%Y).tar

So, if this is what you are looking to do with all your containers, you can run:

for CONTAINER in $(docker ps -a --format '{{.Names}}'); do
    docker commit $(docker ps -a |grep $CONTAINER \
    |awk '{print $1}') ${CONTAINER}_$(date +%d-%m-%Y)
    docker save > ${CONTAINER}_$(date +%d-%m-%Y)

And finally if you want to import your images from the tar files you can run:

docker load  < /backup/${IMAGE_NAME}_$(date +%d-%m-%Y).tar

See you next time!