Volumes are paths on the host mounted inside the container, allowing for persistent storage. Removing a container does not remove the files in the volume, as they are only mounted to the container upon its startup.
There are three types of volumes:
- Named volumes
- they are managed by Docker and created automatically in its storage location, usually /var/lib/docker/volumes
- Unnamed volumes
- these act just like named volumes, but they get a randomly generated name
- Bind mounts
- used to mount specific paths from the host inside a container
All volumes are technically mounts, the difference is that volumes are managed by docker. You can have a volume with a specific path, but that’s more typing for really the same effect. I don’t really see a reason not to use bind mounts.
Syntax
Either in the docker run command, in a compose file, or in a container manager such as Portainer, volumes are usually declared as:
volumes:
- /path/on/host:/path/inside/container
On the left side, you will set the path to the directory or file on the host system, and on the right side is the path the directory/file will be inside the container.
REMEMBER
Left = path on the host/on your machine/server/computer
Right = path inside the container
For example, if you want to store your WordPress installation in /mnt/disk1, you would use the following volume syntax:
volumes:
- /mnt/disk1/wordpress:/var/www/html # Mounting directories
- /mnt/disk1/config/wp-config.php:/var/www/html/wp-config.php # Mounting files
The mount order is from top to bottom, so even if there’s already a wp-config.php in your /mnt/disk1/wordpress directory, the one from /mnt/disk1/config will be inside the container.
Read-only
There are some files which you might not want the container to modify. In that case, you can set the volume as read-only by adding “:ro” to the end of it
volumes:
- /mnt/disk1/wordpress:/var/www/html
- /mnt/disk1/config/wp-config.php:/var/www/html/wp-config.php:ro
Leave a Reply