Making Docker Containers talk to each other by Hostname using container networking
If you’re looking to connect different docker containers — e.g. a node.js server and a redis caching layer — you might have noticed that dockers’ — link flag is outdated and now considered legacy. One solution would be to use Docker Compose for co-independence between containers, but this post assumes you’re using regular old Docker.
The preferred way of going about things is called Docker container networking. In this very short post I will show you how to setup your docker container network and let containers interact with each other by Hostname rather than by IP address.
First, let’s assume that you have a nodejs container that takes the redis URL as an environment variable. You would spin up your container as follows
$ docker --name myNodejs run -d -p 3001:3001 -e REDIS_URL=<url> nodejs
If you run redis on your local machine, it won’t do any good as Docker containers run in their own private networks by default and won’t be able to access anything running on your machine. You could, for example, use a hosted redis solution in this case. But since we’re all about containers, let’s spin up a redis container.
$ docker run --name myRedis -d -p 6379:6379 redis
Now you have two containers running, but they don’t know about each other. This is where Docker container networking comes into play. Let’s create a network called myNetwork
$ docker network create myNetwork
$ docker network list
You’ll see a list of current networks and myNetwork will be one of them. Now, let’s re-create our redis container with the correct flag.
$ docker run --name redis.networked -d -p 6379:6379 --network myNetwork redis
We can see if the container is connected to our network by running the following command
$ docker network inspect myNetwork
You’ll see that redis.networked is running in your network. Excellent! The IP address also shows up, but what container networking allows you to do, is to refer to other containers using their name.
Finally, we will spin up our nodejs container with the correct ENV variable, pointing to our redis container using redis.networked as Hostname.
$ docker run --name node.networked -d -p 3001:3001 -e REDIS_URL=redis://redis.networked:6379 --network myNetwork nodejs
Et voilà! Now your redis container is available in all containers that use the network flag pointing to myNetwork under redis.networked.
Next up I’ll figure out how to deploy this to AWS — Stay tuned. For now I hope this was useful for someone trying to migrate from linked containers to container networking. Cheers!