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
Host path can be defined as an absolute or as a relative path.
version '3' services: app: image: nginx:alpine ports: - 80:80 volumes: - /var/opt/my_website/dist:/usr/share/nginx/html:ro
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
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.
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.