Storage & Volumes
Each docker container has its own isolated volume. By default, this volume isn't persistent, meaning that if the container restarts or gets deleted, then so does its data. There are a few options available for persistent storage.
Specifying volume options
To preface this page, I'd like to touch on the 2 main options available for mounting volumes when using docker run;
-v
-v is the older and less comprehensive way of specifying volume & mount options. Many of the examples below show how to use the -v flag.
--mount
--mount is the more complex but comprehensive method of specifying volume and mount options.
Examples;
Volume mount:
docker run -d --mount type=volume,source=myvolume,target=/app nginx
Bind mount;
docker run -d --mount type=bind,source=/path/on/host,target=/app nginx
Read-only volume:
docker run -d --mount type=volume,source=myvolume,target=/app,readonly nginx
Docker Volumes
You can directly specify a volume using the -v flag during docker run without pre-creating the volume. Docker will automatically create a volume if it doesn't find one matching your specification.
Example;
docker run -v data1:/path/on/container containername
This command will create a data volume, called data1, stored within /var/lib/docker/volumes on the host, for the container to use as persistent storage.
docker volume create data1
This would create a volume called data1, stored within /var/lib/docker/volumes on the host, that can then be mounted to containers for persistent storage.
To mount a pre-existing data volume to a docker container, you would still use the -v flag:
docker run -v data1:/path/on/container containername
This is useful if you want to manage the volume lifecycle explicitly (naming, inspecting, and configuring it before use).When you manually create a volume, you can inspect it, set specific options, and organize your persistent storage more systematically.
Volume Mapping (Bind Mount)
Let's say that you don't want to store your container data within /var/lib/docker/volumes on the host, or you have pre-existing data that you want the container to be able to access. In this case, we can map a host directory to a directory on the container.
docker run -v /path/on/host:/path/on/container containername
Example;
I have a MySQL container that I need to keep persistent data on. To do this, I would map the /var/lib/mysql directory on the container, to a location on the docker host.
docker run -v /opt/mysql_container_data:/var/lib/mysql mysql
Docker Storage Usage
To view Docker's total disk utilisation (images, volumes, etc) on the host machine:
docker system df
You can also pass the -v flag to view detailed info on where this disk space is being consumed:
docker system df -v
No Comments