How to connect two docker instances

Mar. 12, 2022

This article is in WIP

This is usually issue I have seen newbie struggle with. So I am just going to explain how to make two docker network talk to each other. There are essentially two methods:

  1. Make both container in same docker network
  2. Expose the port to the host machine and connect using the host machine on same port

Let’s elaborate the two cases. For both cases, I will include docker-compose way and docker-cli way.

Make both containers in same docker network:

This is straight forward way to do it. All you have to do it create a docker network and assign the network to both the containers.

docker-image

docker-compose way

We will consideer connecting a database to an app service. For these you will generally have docker-compose to manage them both easily.

Let’s say you have the initial version as follow.

version 3:
services:
  cachedb:
    image: redis:latest
    volume:
      - ./app:/app
  app:
    image: myapp:latest

Here, cachedb is the redis database. app is our server.

After adding docker network:

version 3:
services:
  cachedb:
    image: redis:latest
    volume:
      - ./app:/app
    network:
      mynetwork
  app:
    image: myapp:latest
    network:
      mynetwork
networks:
  mynetwork:
    driver: bridge

Notice, we have defined a bridge network and called it mynetwork. And then, assigned it to both the services.

Docker CLI version

docker network create mynetwork
docker run redis --network=mynetwork --name cachedb -d
docker run app --network=mynetworkl --name app  -d

Since both the containers share the same docker network, to connect the app to the cachedb we will refer the redis instance with the alias name and docker will be able to resolve the alias name to the IP address of the container.

For example to connect the redis instance, we will use the following:

REDIS_URL = "redis://cachedb:6379"

Note: instead of localhost we are instead referring it by the alias name. This means you don’t need to worry about keeping track of containers’ IP addresses, which can frequently change.

Through the host machine

Warning: Don’t use this in production as you will have to keep track of the host IP. Always create a docker network to connect docker containers.

When you start a container without specifying docker network, Docker will create a default network called bridge. And all container are added into bridge network automatically. In a bridge network, each container is assigned its own IP addres. You can find out IP using the following command.

docker inspect app | jq '.[].NetworkSettings.Networks.bridge.IPAddress' 

Lets see how it would look like as code.

docker run redis --port=6379:6379