Copy data from one data volume to another

Recently I've played around with Docker and CoreOS I made some mistakes in the beginning. When I discovered that my data volume is based on the same image as the container which is supposed to use it (therefore wasting disk space) I wanted to move my data from the old one to the new, smaller one. Here's how you do it:

Create plain data volume

Note: you don't have to create it if you already have a container/volume you want your data to be copied into.

$ docker run -v /ghost_override --name ghost-data busybox \
	echo "Data-only container for Ghost"

Where:

  • /ghost_override is the dir where volume will be mounted (inside of the container)
  • ghost-data is the friendly name for this container
  • busybox is a very small (about 2.5MB) image great for data volumes

Copy data from old container to the host system

$ docker run --rm -v /tmp/ghost_override:/host:rw --volumes-from ghost-old busybox \
	cp -r /ghost_override/ /host

What we do here:

  • --rm will remove this container after it's finished
  • -v /tmp/ghost_override:/host:rw will mount host's /tmp/ghost_override dir to /host dir inside the container in read-write mode
  • --volumes-from ghost-old will use the old container's volumes we want to copy
  • cp -r /ghost_override/ /host will copy contents of old volume to our host dir

Copy data from the host system to the new container

$ docker run --rm -v /tmp/ghost_override:/host:ro --volumes-from ghost-data busybox \
	cp -a /host/ghost_override/ /ghost_override

This will:

  • -v /tmp/ghost_override:/host:ro mount host's /tmp/ghost_override dir to /host dir inside the container in read-only mode
  • --volumes-from ghost-data use new container's volume
  • cp -a /host/ghost_override/ /ghost_override copy data to our new container

Then you can remove /tmp/ghost_override dir, ghost-old container (docker rm ghost-old) and start using new container's volume (--volumes-from ghost-data).