Shared docker volume mounts host directory

Viewed 116

I like to mount a specific directory on my host machine an two containers. Everything is defined in a docker-compose.yaml file.

In the services section of the yaml file, for both containers, the following is specified:

volumes:
- myvolume:/internal/path

In the volume section, the volume is defined as:

volumes:
    myvolume:
        driver: local

The shared volume is located in /var/libs/docker/volumes as a single file by default. Now, I want to specify a directory in the host's file system, let's say directory /host/directory. Can somebody please state how to realize that by means of docker-compose?

1 Answers

Sharing host volumes with docker services is done by specifying the volume in the service section like this:

# ...
    volumes:
      - /path/in/host:/path/in/service
# ...

Multiple services may use the same host volume.

To give a more complete example, a docker-compose.yaml mounting a Linux host directory into multiple docker services could e.g. look like this:

version: "3.3"
services:
  service_1:
    image: alpine
    volumes:
      - ./shared_host_directory:/path/in/service_1
    command: >
      /bin/sh -c "echo 'A message from service 1' >> /path/in/service_1/output.log"

  service_2:
    image: alpine
    volumes:
      - ./shared_host_directory:/path/in/service_2
    command: >
      /bin/sh -c "echo 'A message from service 2' >> /path/in/service_2/output.log"

If you execute this example using the following commands

mkdir -p shared_host_directory  # Make sure that the shared host directory exists.
rm -rf shared_host_directory/output.log  # Make sure that the output file does not exist yet.
docker-compose up  # Execute the docker-compose.yaml file until both services terminate.
cat shared_host_directory/output.log  # Get the output of the created log file.

then the displayed content of shared_host_directory/output.log should look similar to this:

A message from service 1
A message from service 2

Note that the lines might be switched due to the race condition between the services 1 and 2. Of course, you could also replace the relative path in the docker-compose.yaml by an absolute path.

Citing the docker compose file reference, https://docs.docker.com/compose/compose-file/compose-file-v3/#volumes,

You can mount a host path as part of a definition for a single service, and there is no need to define it in the top level volumes key.

Please note that the link above also contains further examples on the usage of volumes with docker-compose.

Related