Docker - 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.
Volumes in Docker
Creating a new, persistent, Docker volume
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