Purpose

The purpose of this post is to review how we can use volumes in docker-compose. These are some possible scenarios:

  • Use one/various volume by one service/container.
  • Use one/various volumes by one set of services (defined in the same docker-compose).
  • Use one/various volumes across the Docker installation.

Before you begin

In this tutorial will learn how to use volumes in Docker Compose. A Linux/Mac OS/Windows machine with Docker and Docker Compose installed is required to follow this tutorial.

Types of volumes

Host mounting volumes

Syntax: /host/path:/container/path

Host path can be defined as an absolute or as a relative path.

Example:

version '3'

services:
  app:
    image: nginx:alpine
    ports:
      - 80:80
    volumes:
      - /var/opt/my_website/dist:/usr/share/nginx/html:ro

Named volumes

Syntax: named_volume_name:/container/path

Named volumes can be defined as internal (default) or external.

Internal Named volumes

Internal named volumes have the scope of a single docker-compose file and Docker creates them if they don’t exist.

docker-compose.yml file example with a named volume web_data:

version '3'

volumes:
  web_data:

services:
  app:
    image: nginx:alpine
    ports:
      - 80:80
    volumes:
      - web_data:/usr/share/nginx/html:ro

External Named volumes

External named volumes can be used across the Docker installation and needs to be created by the user (otherwise fails) using the docker volume create command.

Example:

Defines web_data volume:

docker volume create --driver local \
    --opt type=none \
    --opt device=/var/opt/my_website/dist \
    --opt o=bind web_data

docker-compose.yml file with a named volume web_data defined externally:

version '3'

volumes:
  web_data:
    external: true

services:
  app:
    image: nginx:alpine
    ports:
      - 80:80
    volumes:
      - web_data:/usr/share/nginx/html:ro

There are different volume types like nfs, btrfs, ext3, ext4 and also 3rd party plugins to create volumes.

See Docker Compose volume reference for more info.