Table of contents
This allows you to persist data and files to your host machine instead of the "virtual" one (container).
For example, a volume that maps to your local /var/lib/mysql allows the MYSQL database files to be persisted to your local machine, which means if you squash and start a new container with the same volume mapping your data should be available in the new container.
Attaching a volume to a new container
If you are about to spin a new container from an image with a volume attached this is straightforward:
$ docker run -v <local_path>:<container_path>
Attaching volumes to a running container
You can't attach a volume to a running container, you can however start a container with one.
Let's say you already have a running container and starting a new one will mean losing some changes you made to the running container.
We can follow a two-step process to get around this.
Step 1 (Container to image)
Since we can only attach a volume to a new container, we need to convert our running container into an image then we can start a new container based on the new image.
We use the Docker commit [↗] command for this.
01: docker commit <container_id> <new_image_name>
03: # eg
04: docker commit 277356 my_new_image
:This is the ID of the running container. You can view details of all running containers using docker ps. :This will be the name of the new image that will be created.
Step 2 (From an image to a container with a volume attached)
To spin a new container with a volume we will be using the
Here is the command structure
docker run -v
Let's assume the following:
- Saved image name: my_new_image
- Local path: /home/user/mySite
- Container path: /var/www/
The resulting command will be:
$ docker run -v /home/user/mySite:/var/www my_new_image
You can and should of course add all the other command flags you need.
Note that if you are running a different OS (host OS) from the one the container is based on, you might not be able to mount a volume, especially if the path you are mapping is a systems directory. A mapping for a path like /var/www might work fine, but maybe not /var/lib.
Here is another article you might like 😊 "How To Copy Files/folders Between A Docker Container And Your Local Filesystem"