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.


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=nginxtest \
  --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:
  frontend:
    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.


CategoryRicottone