Docker Volume

Docker Volume is the perfered way to persist data.

There are three types of mount

  • volume - volume created and managed by Docker
  • bind mount - share file or directory with host
  • tmpfs mount - only for Docker on Linux

Volume

When a container is stopped, the data in the container layer is lost forever. Docker uses Volume to persist data so that applications like database, nosql database can keep their data.

All Docker volumes are stored in /var/lib/docker/volumes/ in the host filesystem. Docker Volume is stored as normal directories and files on the host system.

You can share volume between containers, just mount the volume to different container.

Create Volume

1
2
# create a  volume, new directory is created in /var/lib/docker/volumes/
docker volume create myVol

To inspect the volume

1
docker volume inspect myVol

List Volumes

1
docker volume ls

Mount a volume

We can mount a volume to a container using -v option of docker run command.

Format is -v volume-name:container-path

Example to mount a volume

1
docker run --rm --name volumetest -it -v myVol:/data alpine /bin/sh

Changes made to the volume in the running container are persisted

1
2
cd /data
echo "foo" > file1

You can verify the changes are made by printing the file in the myVol volume

1
cat /var/lib/docker/volumes/myVol/_data/file1

Remove Volumes

remvoe a volume

1
docker volume rm myVol

remove volumes not being used

1
docker volume prune

Bind Mount

bind mount allows you to mount a host file or directory to a running container.

Format is -v host-path:container-path

Example to bind myData directory to a running container’s /data directory

1
docker run --rm --name mounttest -it -v $(pwd)/myData:/data alpine /bin/sh

Example. mount a site directory to a running nginx container. Nginx container will serve the site at host port 8000

1
docker run --name myNginx -v $(pwd)/site:/usr/share/nginx/html -p 8000:80 -d nginx:alpine

Define volume in Dockerfile

If an application wants to persist data, the application must define the absolute path(s) in the container to be used as volume. This allows the container and host to share volumes.

Example to use VOLUME instruction to define a mount point /data/db in the container’s filesystem.

1
VOLUME ["/data/db"]

Note that if you don’t use -v option to provide a volume or bind mount, Docker automatically create a volume.

You can check the mount point of the container using docker image inspect command.

example

1
docker image inspect  --format='{{json .ContainerConfig.Volumes}}' couchdb:latest | jq

result

1
2
3
{
"/opt/couchdb/data": {}
}

Reference