Communicating between Docker containers in different networks on the same host

In this guide, I will explain how to connect two containers in different docker-compose.yml Services together that are setup on the same host machine.

By default every docker-compose.yml Service is generating its own bridge-Network so that containers inside can communicate between each other.

But communications between two docker-compose.yml Services on the same host machine are blocked by docker. So we need to create a new "custom" bridge-Network if two containes in different docker-cmpose.yml Services need to communicate between each other.

header

In this example I want to connect web-app1 container with the DB2 container from different docker-compose.yml Services.

More information about this topic can be found on the offical docker documentation: https://docs.docker.com/compose/networking

  1. We need to create the custom bridge-Network:

    For the custom bridge-Network you can use your own name. In my example I chose the name serv1_link_serv2

    sudo docker network create -d bridge serv1_link_serv2
  2. Now create the two docker-compose.yml files and connect web-app1- and db2-container together over the serv1_link_serv2 bridge-Network.

    docker-compose1.yml

    version: "3"
    services:
     db1:
       image: "mariadb:latest"
       ........
    
     web-app1:
       image: "php:apache"
       ........
       networks:
         - serv1_link_serv2
         - default
    
    networks:
     serv1_link_serv2
       name: serv1_link_serv2
       external: true

    docker-compose2.yml

    version: "3"
    services:
     db2:
       image: "mariadb:latest"
       ........
       networks:
         - serv1_link_serv2
         - default
    
     web-app2:
       image: "php:apache"
       ........
    
    networks:
     serv1_link_serv2
       name: serv1_link_serv2
       external: true

Previous Post Next Post

Add a comment