Docker Networking and Cross Container Communication

Docker Networking and Cross Container Communication

A container is an isolated running environment for your code. It does not know the operating system or the directories in your system. Even though containers are isolated running pieces of code, they might need to interact with the outside environment. Either the world wide web, host system or other services running inside different containers.

As far as interacting with the world wide web is concerned, containerized applications can make requests without any configuration just as they would, had they not been containerized. When it comes to interacting with the host system or other running containers, we need to configure Docker containers. These are the two cases we will look into.

Disclaimer - We are dealing with containers running on a single host.

Container to Localhost Connection

When we want to receive or send requests to a service or a database running on localhost, we cannot do it directly as Docker containers are isolated and ignorant of the operating system or host's filesystem. There is a very simple solution to this problem. We need to replace all the 'localhost' with 'host.docker.internal' as the hostname. This will ensure that all outgoing requests are resolved to the localhost IP.

Container-to-Container Connection

Docker containers can interact with one another using networking. It means that a container will create a connection to a port on another container. There are two ways to go about that.

  1. Bridge Networking - The simplest and default network in Docker is the bridge network. It allows simple container-to-container communication by IP address. To make connection requests to another running container, go to the terminal and look up the container's IP address in the network settings using docker container inspect. Now use this IP address as the hostname. As simple as that.

  2. User-Defined Bridge - You can define your custom bridge network and be very explicit about who joins it. It gives us the added advantage of addressing containers through their name or alias. For example, if we have a running MongoDB container named 'mymongo', we can easily interact with it using the 'mymongo' as the hostname - 'mongodb://mymongo:27017'.

    We can easily add containers to networks by using the --network <NETWORK NAME> when executing docker run in the terminal. However, if the network does not exist, we will have to create it first manually.

    To create a new network, use docker network create <NEW_NETWORK_NAME> in the terminal.

    Now, the containers in the same network can elegantly interact with each other, addressing each other by their names or aliases.

Hopefully, this short article on Docker networking and cross-container communication was helpful to you.