dockerdocker-compose

Communication between multiple docker-compose projects


I have two separate docker-compose.yml files in two different folders:

How can I make sure that a container in front can send requests to a container in api?

I know that --default-gateway option can be set using docker run for an individual container, so that a specific IP address can be assigned to this container, but it seems that this option is not available when using docker-compose.

Currently I end up doing a docker inspect my_api_container_id and look at the gateway in the output. It works but the problem is that this IP is randomly attributed, so I can't rely on it.

Another form of this question might thus be:

But in the end what I'm looking after is:


Solution

  • You just need to make sure that the containers you want to talk to each other are on the same network. Networks are a first-class docker construct, and not specific to compose.

    # front/docker-compose.yml
    services:
      front:
        ...
        networks:
          - some-net
    networks:
      some-net:
        driver: bridge
    

    ...

    # api/docker-compose.yml
    services:
      api:
        ...
        networks:
          - front_some-net
    networks:
      front_some-net:
        external: true
    

    Note: Your app’s network is given a name based on the “project name”, which is based on the name of the directory it lives in, in this case a prefix front_ was added

    They can then talk to each other using the service name. From front you can do ping api and vice versa.