Docker Containers and volumes

Share the page with

When the default disk space allocated to a container is not appropriate for the job at hand, In these cases we need storage that can persist between container deployments.

In such case we use --mount or -v option.


Volumes are the preferred mechanism for persisting data generated by and used by Docker containers.

While bind mounts are dependent on the directory structure and OS of the host machine, volumes are completely managed by Docker.

Volumes have several advantages over bind mounts:

In addition, volumes are often a better choice than persisting data in a container’s writable layer, because a volume doesn’t increase the size of the containers using it, and the volume’s contents exist outside the lifecycle of a given container.

If your container generates non-persistent state data, consider using a tmpfs mount to avoid storing the data anywhere permanently, and to increase the container’s performance by avoiding writing into the container’s writable layer.

We can specify the volume by using --volume or -v option.

docker container run --rm -it --name alpine_linux --volume "$(pwd)"/tests:/tests ubuntu:latest /bin/bash

Read only:

docker container run --rm -it --name alpine_linux --volume "$(pwd)"/tests:/tests:ro ubuntu:latest /bin/bash

Backing up data

docker run -v /dbdata --name dbstore ubuntu /bin/bash

In the next command:

docker run --rm --volumes-from dbstore -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /dbdata

When the command completes and the container stops, it creates a backup of the dbdata volume.

See how to restore volume from backup

Removing volumes

A Docker data volume persists after you delete a container. There are two types of volumes to consider:

To automatically remove anonymous volumes, use the --rm option. For example, this command creates an anonymous /foo volume. When you remove the container, the Docker Engine removes the /foo volume but not the awesome volume.

docker run --rm -v /foo -v awesome:/bar busybox top

If another container binds the volumes with --volumes-from, the volume definitions are copied and the anonymous volume also stays after the first container is removed.

To remove all unused volumes and free up space:

docker volume prune
Share the page with