Skip to content

Instantly share code, notes, and snippets.

@Ratler
Last active August 27, 2021 17:30
Show Gist options
  • Save Ratler/7756deecc330db9ce07a to your computer and use it in GitHub Desktop.
Save Ratler/7756deecc330db9ce07a to your computer and use it in GitHub Desktop.
A few quick bash one-liners to export/save import/load docker containers/images

NOTE: make sure you export containers and images in separate directories or it's very likely there will be issues when importing or loading your backups using the following snippets

Export all containers

$ while read image container_id; do 
    docker export $container_id > ${image////_}-${container_id}.tar 
  done < <(docker ps -a -f status=exited | tail -n +2 | awk '{ print $2 " " $1 }')

Import containers (as versioned images)

$ for file in *.tar; do
    eval `echo $file | sed -nr 's;([a-zA-Z0-9\.-]+)_([a-zA-Z0-9-]+)-([a-f0-9]+)\.tar;IMAGE=\1/\2\nVERSION=\3;pg'
    cat $file | docker import - ${IMAGE}:${VERSION} 
  done

Save all images

$ while read image version image_id; do 
    docker save $image_id > ${image////_}-${version}-${image_id}.tar
  done < <(docker images| tail -n +2 | grep -v '<none>' | awk '{ print $1 " " $2 " " $3 }')

Load all images

$ for image in *.tar; do docker load < $image; done
@aemaem
Copy link

aemaem commented Oct 5, 2017

For the "Export all containers" I needed to replace ${image////_} with ${image//\//_}, i.e. escape the to-be-replaced slash.
However, these scripts are very helpful to me! Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment