Volumes and Bind Mounts

Files inside the container are on a virtual filesystem. You cannot directly access the files inside the container, and the container cannot normally access your files. You should think of docker containers somewhat as Virtual Machines.

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


Think of it as plugging in a USB stick. The path on the left is the actual USB stick, and the path on the right is where you can access it on your computer, or in this case, the container.

On Windows you get a drive letter, maybe E:\, and on Linux it’s probably in some /media, /cdrom, /mnt or other folders depending on your distro.

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA ImageChange Image