Docker Volumes

Volumes are file objects that dockerd(8) manages for a container. While they are written to the host file system, users should only interface with them as a volume name.

Compare to Bind Mounts.


Creating Volumes

To create a new volume, try:

docker volume create my-vol

A container can be created with an existing volume mounted into it.

docker run --interactive --tty --rm --name my-alpine \
  --mount src=my-vol,dst=/app \
  alpine:latest

A container can also be created with a new volume.

docker run --detach --name=my-nginx \
  --mount src=nginx-vol,dst=/usr/share/nginx/html \
  nginx:latest

The volume is implicitly created and the contents of the destination directory are written into the newly-initialized volume.


Destroying Volumes

After a container is stopped and destroyed, any volumes used will persist. This may or may not be desirable.

To list all volumes, try:

docker volume ls

To delete a volume, try:

docker volume rm my-vol


Docker Compose

Volumes are very common with Docker Compose as the use of a volume abstracts away the local filesystem in a way that sidesteps common issues for reproducibility and reuse.

To use a volume, create a docker-compose.yml file like:

services:
  app:
    image: node:lts
      - type: volume
        source: myapp
        target: /home/node/app

volumes:
  myapp:

There is also a shorter syntax.

services:
  app:
    image: node:lts
    volumes:
      - myapp:/home/node/app

volumes:
  myapp:

This can create a need to review and manually delete volumes on a recurring basis. See above for details.


Alternative Drivers

All of the above examples make use of the local volume driver, which simply means that volumes are managed locally.

Alternative volume drivers exist primarily for distributed and highly available deployments. In some cases, volumes can be shared by multiple containers.

As an example, try:

docker plugin install --grant-all-permissions vieux/sshfs
docker volume create \
  --driver vieux/sshfs \
  --opt sshcmd=test@node2:/home/test \
  --opt password=testpassword \
  ssh-vol
docker run --detach --name sshfs-container \
  --volume-driver vieux/sshfs \
  --mount src=ssh-vol,dst=/app,volume-opt=sshcmd=test@node2:/home/test,volume-opt=password=testpassword \
  nginx:latest


CategoryRicottone

Docker/Volumes (last edited 2023-04-05 14:40:48 by DominicRicottone)