Containers communication

Containers communication#

In this page I want to focus on ways of organising container communication.

Communicating by IP#

To access one container from another by container name, you need to add them to the same custom Docker network. However, if you’re using the containers’ IP addresses, the containers can communicate with each other on the default bridge network.


Consider the example where we are trying to send a request from example_client to the example_server container. The following cell creates everything we needed:

docker run -itd --name example_client --rm alpine
docker exec example_client apk add curl &> /dev/null

docker run -itd --name example_server --rm kennethreitz/httpbin
ea3dc18555a4c4f8458da8333802a60484e9ef92df9ca8fd2998d7f8f6d6d5f9
e5da80689cabd318d696d8640cd2ba0ad55935ccfabd379c8bf0f34e7cc5efa5

Obviously we can’t do this just by container name. This is because the containers are in the default bridge network, which doesn’t support such interactions.

docker exec example_client curl -s example_server/anything

Now let’s try to extract the ip address of server_example on the docker network.

server_ip=$(docker inspect\
    --format '{{ .NetworkSettings.IPAddress }}'\
    example_server)
echo $server_ip
172.17.0.3

By using it in the curl that tries to access server_example from client_example we’ll have result.

docker exec example_client sh -c "curl -s $server_ip/anything"
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Host": "172.17.0.3", 
    "User-Agent": "curl/8.9.0"
  }, 
  "json": null, 
  "method": "GET", 
  "origin": "172.17.0.2", 
  "url": "http://172.17.0.3/anything"
}

Keep environment clean after all.

docker stop example_client example_server
example_client
example_server