Define Docker Container Networking So Containers Can Communicate

So I was recently playing with Docker using a mixture of docker-compose and the docker commands and I found myself with a container communication issue.  I was trying to spin up a container to communicate with containers launched via docker-compose, but my new container couldn’t find these other containers.  This is because there was a networking issue between how the Compose containers were running, versus vanilla.

So what do you need to do when it comes to networking and communication between containers?

Let’s run through the scenario I was using.  I had a Compose setup that deployed a cluster of NoSQL databases.  Later I wanted to deploy a Java application, but I was too lazy to add it to the docker-compose.yml file.  The problem was that this Java application couldn’t see any of the databases in the cluster by hostname or IP address.

We can troubleshoot this by inspecting both the containers deployed with Compose and without.  So let’s assume database is a container deployed by Compose and application is a container deployed without.

Now run the following command:

After running the above command to inspect the running database container, you might get results that contain the following few lines:

In particular notice the docker_default property.  This is the network in which the container is a part of.

Now let’s inspect the other container:

After running the above command, you might get results similar to the following:

Notice that the network is bridge for this container which means our containers are not on the same network.  Of course our containers cannot communicate to each other if they are not on the same network.

Instead we need to add our application to the Compose or define the network when deploying the container.  Let’s go with the scenario where we want to define the network.

When running the application container, it might look something like this:

In the above command notice the --network="docker_default" property.  This means we are deploying the container on the docker_default network rather than the bridge network.

With both containers on the same network they can now communicate with each other.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.