I am trying to set up a database container but I realized that every time I stop and remove the container, my data is lost. How exactly do I use the -v or --volume flag to map a local directory to a path inside the container? I want to make sure I understand the difference between bind mounts and named volumes, and how to verify the data is actually being persisted on my host machine.
3 answers
To start a container with a volume, the most common method is the -v flag. For a named volume, use docker run -d -v my_data:/var/lib/mysql mysql. This creates a managed volume called "my_data." If you prefer a bind mount (mapping a specific host folder), use the absolute path: docker run -d -v /home/user/sql_data:/var/lib/mysql mysql. Using volumes ensures that even if the container is deleted, the data remains intact in the Docker storage area or your specified host path. For newer setups, the --mount flag is preferred as it is more verbose and explicit about the source and destination types, which helps prevent errors with non-existent directories.
Have you looked into whether you need read-only or read-write permissions for that specific volume mapping? By default, Docker mounts volumes as read-write, but if you are just sharing configuration files, adding :ro to the end of your volume string can significantly improve the security of your container by preventing the process from accidentally modifying your host files.
The easiest way is using docker volume create first, then referencing it in your run command. This keeps your Docker environment much cleaner and more organized than using long file paths.
I agree with Heather. Named volumes are much easier to manage with the docker volume prune command later on, and you don't have to worry about the specific folder structure of the host machine you are currently working on.
Jason, that is a great security tip. To implement what you're saying, the syntax would look like -v /host/config:/container/config:ro. I’ve used this frequently with Nginx containers where I want to provide the .conf files but don't want the web server process to have any ability to overwrite them. It definitely reduces the attack surface if the container were ever compromised.