Daniel Jakobsen Hallel
Daniel Jakobsen Hallel

Reputation: 584

docker-compose share local bind volume between multiple services

I have a docker compose file for a mono repo. I have multiple services that use the same code, all the shared code is in the following folder structure:

* root
|-- * shared
-   | -- * sharedA
    |    | -- src
    |    -
    | -- * sharedB
    -    | -- src
         -

When i run my services in development (from docker compose) I'm using a watch program that watches changes on shared/sharedA/src, shared/sharedB/src

my docker compose file looks something like this

version: '3'
services:
  service_a:
    build:
      context: .
      dockerfile: 'services/serviceA/Dockerfile'
    volumes:
      - ./services/serviceA/src/:/usr/src/app/services/serviceA/src
      - ./shared/sharedA/src/:/usr/src/app/shared/sharedA/src
      - ./shared/sharedB/src/:/usr/src/app/shared/sharedB/src

  service_b:
    build:
      context: .
      dockerfile: 'services/serviceB/Dockerfile'
    volumes:
      - ./services/serviceB/src/:/usr/src/app/services/serviceB/src
      - ./shared/sharedA/src/:/usr/src/app/shared/sharedA/src
      - ./shared/sharedB/src/:/usr/src/app/shared/sharedB/src

My goal is to have the volumes declaration of

- ./shared/sharedA/src/:/usr/src/app/shared/sharedA/src
- ./shared/sharedB/src/:/usr/src/app/shared/sharedB/src

in a central place that will allow me to define them once and import/connect them in each service,

tried going through this guide + docker compose docs
http://blog.code4hire.com/2018/06/define-named-volume-with-host-mount-in-the-docker-compose-file/
with some alterations to achieve it, but unfortunately i couldn't get it working..

I'm not sure it's even possible but the documentation about docker compose volumes isn't really helpful so i thought maybe someone here already dealt with something similar 🙂

Upvotes: 1

Views: 1785

Answers (1)

Mounir Messaoudi
Mounir Messaoudi

Reputation: 373

You can use named volumes:

  version: '3'
services:
  service_a:
    build:
      context: .
      dockerfile: 'services/serviceA/Dockerfile'
    volumes:
      - sharedA:/usr/src/app/shared/sharedA/src
      - sharedB:/usr/src/app/shared/sharedB/src

  service_b:
    build:
      context: .
      dockerfile: 'services/serviceB/Dockerfile'
    volumes:
      - sharedA:/usr/src/app/shared/sharedA/src
      - sharedB:/usr/src/app/shared/sharedB/src


volumes:
  sharedA:
    driver: local
    driver_opts:
      type: none
      device: ./shared/sharedA/src/
      o: bind
  sharedB:
    driver: local
    driver_opts:
      type: none
      device: ./shared/sharedB/src/
      o: bind

Upvotes: 3

Related Questions