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.
To have persistent data on a container, you have to map a directory on the docker host, 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
There are 2 methods that can be used to create a docker volume;
- Using docker run -v without creating a volume beforehand:
You can directly specify a volume using the-vflag duringdocker runwithout pre-creating the volume. Docker will automatically create a volume if it doesn't find one matching your specification. - You can create a volume manually using
docker volume createbefore running the container:
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.
To mount a pre-existing data volume to a docker container, you would still use the -v flag:
docker run -v volume_name:/path/on/container containername