Docker-compose and volumes

Viewed 2164

When I create a volume manually and include it in docker-compose, if I don't prefix the volume tag with docker_, docker compose creates a new volume prefixed with docker_ For example: I create a volume with:

docker volume create myvolume

It's visible at /var/lib/docker/volumes/myvolume. I include it in my docker-compose yaml file, but when I run docker-compose, a new volume is created at /var/lib/docker/volumes/docker_myvolume If I call my volume docker_myvolume and include that in my docker-compose yaml, it uses it and doesn't create it's own.

Is this normal behavior?

2 Answers

You need to set external: true to tell docker-compose that this volume has been created outside of Compose; otherwise, Compose will attempt to create a volume called [projectname]_myvolume.

In the example below, docker-compose up does not attempt to create the volume, instead it raises an error if it doesn’t exist.

volumes:
  myvolume:
    external: true

Yes, Compose generally prefixes things with its project name. This includes containers, networks, and named volumes. In general, if you actually need to interact with these things, there is an equivalent docker-compose command that chooses the correct name (e.g., docker-compose exec).

In general you shouldn't be directly modifying things inside /var/lib/docker. That directory tree is Docker's private state and there are no particular guarantees about the format of files there. If your use case involves directly interacting with the volume files from the host, either use a /host/path:/container/path bind mount or explicitly specify the storage location using volume options.

Related