Simple Network Communications in Docker Without Compose

I often run services like databases or messaging systems in Docker and connect to them from my host computer, where I have a .NET application using them.

But sometimes I want to run the application in a container too. In this case, I have to connect the two containers over a Docker network.

In this post, I’ll show how to do it without Docker Compose, and in a follow-up post, I’ll use Docker Compose.

Set up the network

First, I create a Docker network that both containers will use to communicate.

docker network create app_to_app_network

That’s all there is to it.

Run the two containers

I’m using Alpine for this simple example because it’s small and starts quickly.

Connecting the containers to the network is part of the command to run the containers.

Open a terminal and run this -

docker run -it --rm --name alpineone --network app_to_app_network alpine

Open another terminal and run this -

docker run -it --rm --name alpinetwo --network app_to_app_network alpine

This runs two containers named alpineone and alpinetwo, connects them to the app_to_app_network network, and starts the shell inside the containers.

Test the connection

From the first container -

ping alpinetwo

You should see output like this -

PING alpineone (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.111 ms
64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.119 ms
64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.176 ms

From the second container -

ping alpineone

You should see output like this -

PING alpineone (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.111 ms
64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.119 ms
64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.176 ms

There you go! Two containers communicating over a Docker network.

For fun, you could also use nc to send messages between the two containers.

In the first container, run this to listen on port 8888 -

nc -l -p 8888

In the other container, run this to send a message -

nc alpineone 8888
# type your message and hit enter

You should see the message appear in the first container.

comments powered by Disqus

Related