Managing Docker Volumes

Docker volumes are great for storing persistent data in one spot. Sometimes,
though, you need to get a volume from one place to another — something that isn’t obvious how to do.

While Docker images are easily shipped around as tar archives via docker save and docker load, there aren’t yet commands for volumes to do the same thing.

Fortunately, since volumes can be mounted into any container we like, getting data out is a simple matter of running a tar command in a throwaway container. Just make sure that any containers that might be using those volumes are shut down first!

# Export to stdout
docker run --rm -v $VOLUME:/data -w /data alpine tar czf - ./
# Import from stdin
docker run --rm -i -v $VOLUME:/data -w /data alpine tar xzf -

Using the above commands, you can stream volumes to wherever you might need them.

# Backup to S3
docker run --rm -v $VOLUME:/data -w /data alpine tar czf - ./ \
  | aws s3 cp - s3://mybucket/$VOLUME-`date +%s`.tar.gz

# Restore from a local file
docker run --rm -i -v $VOLUME:/data -w /data alpine tar xzf - \
  < myvolume.tar.gz

# Transfer over SSH
# (If bandwidth is not a concern, remove the "z" from both tar commands to
# disable compression and potentially speed up the transfer.)
docker run --rm -v $VOLUME:/data -w /data alpine tar czf - ./ \
  | ssh myhost.example.com \
    "docker run --rm -i -v $VOLUME:/data -w /data alpine tar xzf -"