# How we can use volumes in Docker Compose

In 
Published 2022-12-03

This tutorial explains how we can use volumes in Docker Compose.

# Short explanation

Here are some points to underline:

  • by default data in Docker containers is not persistent (the data doesn’t persist when that container no longer exists)
  • in order to persist that data we need to store files on the host machine. We have 2 options here:
    • volumes
    • bind mounts

volumes :

  • Are stored in a part of the host filesystem which is managed by Docker (/var/lib/docker/volumes/ on Linux).
  • Non-Docker processes should not modify this part of the filesystem.
  • Volumes are the best way to persist data in Docker.

bind mounts :

  • May be stored anywhere on the host system.
  • They may even be important system files or directories.
  • Non-Docker processes on the Docker host or a Docker container can modify them at any time.

# Volume usage in Docker Compose

In order to use a volume, we need to create it.

Supposing we have the docker-vol1 volume created, we can use it when we define a container in Docker Compose:

version: '4.15'
services:
  apache:
    image: httpd:latest
    container_name: my-app-container
    ports:
    - '8080:80'
    volumes:
      - docker-vol1:/app
      
volumes:
  docker-vol1:

Running docker compose up for the first time creates a volume. The same volume is reused when you subsequently run the command.

In the following example if docker-vol1 volume is not created/available, the container will not start because of external: true.

version: '4.15'
services:
  apache:
    image: httpd:latest
    container_name: my-app-container
    ports:
    - '8080:80'
    volumes:
      - docker-vol1:/app
      
volumes:
  docker-vol1:
     external: true