NOTE: The purpose of this article is to give an quick overview (so not a detailed one) of docker volumes with some pointers. And before you start it is good to read about Docker storage drivers
What?
What is Docker Volumes?
Docker volumes is a mechanism for persisting data generated by and used by Docker containers. In a more technical way, volumes are directories that are outside of the default Union File System and exist as normal directories and files in the host filesystem.
Why?
Why do we need volumes? What are the use cases?
- Log files and databases need to persist even when the container is removed.
- For sharing data across the containers.
So if you don’t use volumes(or bind mounts) you many end up loosing valuable data along with your container.
How?
The docker volume works by mounting a container directory to the host filesystem. So all the reads and writes happens to the host filesystem and no the UFS. This makes it possible to persist data and share data.
There are different ways to specify volumes(-v or -mount). In the docker compose file you can add volumes via following ways (this can change depending on the version of your docker compose file).
volumes:
# Just specify a path and let the Engine create a volume
- /var/lib/mysql
# Specify an absolute path mapping
- /opt/data:/var/lib/mysql
# Path on the host, relative to the Compose file
- ./cache:/tmp/cache
# User-relative path
- ~/configs:/etc/configs/:ro
# Named volume
- datavolume:/var/lib/mysql