Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ZigZagT/dbab588a9f2687f7eb33cf080beab69f to your computer and use it in GitHub Desktop.
Save ZigZagT/dbab588a9f2687f7eb33cf080beab69f to your computer and use it in GitHub Desktop.
Backup / Restore docker images with Docker for Mac

This script can help you save time from downloading/rebuild docker images when you want to use Factory Reset or Resize Disk Image in Docker for Mac which deletes all local images.

MAKE SURE YOU HAVE ENOUGH DISK SPACE AVAILABLE

If you have Time Machine enabled, You can use this command to free up a significant amount of disk space:

tmutil thinlocalsnapshots / 10000 4

For me, I have around 30 images on my dev machine which takes around 25GB on-disk space to backup.

The backup size would be much larger than the size given by docker system df because storage layers are shared between images when it's in docker but not shared in backups.

CLOSELY MONITOR DISK SPACE USAGE DURING BACKUP

Once the disk is full, it would trigger OOM which randomly kill your living applications, You would have to do hard reboot to fix it.

Usage

Backup images:

./save_images.sh

Will back all docker images with non-none name and tag to directory images-<date>-<random>

Restore images:

./restore_images.sh <images-backup-directory>
#!/usr/bin/env bash
for image in $(find $1 -type f -name '*.tar'); do
echo loading $image
docker load -i $image
done
#!/usr/bin/env bash
OUT_DIR=${1:-images-$(date +%F)-$RANDOM}
mkdir -p $OUT_DIR
for image in $(docker images --format '{{ .Repository }}:{{ .Tag }}' | grep -v '<none>'); do
OUT_NAME=$(echo $image | tr "/" ":")
if [[ -f "$OUT_DIR/$OUT_NAME.tar" ]]; then
echo $image "->" $OUT_NAME.tar already exists, skipping...
continue
else
echo $image "->" $OUT_NAME.tar
# docker save $image | gzip > $OUT_DIR/$OUT_NAME.tgz # very slow & buggy on mac
docker save -o $OUT_DIR/$OUT_NAME.tar $image
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment