Link docker containers via their internal ip address

There could come a time when you’ll need to link two or more docker containers. For example, you have a database and a web-service running in separate docker containers. The web-service needs data from the database to serve up its services to a third container which is running a tomcat website. This is known as a ‘micro service application architecture‘.

Let’s link docker containers!

Here’s a simple example of two containers¬† – one being able to see the other over their own private internal network.

First, let’s spin up a¬†postgres database container in daemon mode (back ground process (-d) ). Let’s name the database container ‘database’.

# docker run -d --name database postgres:latest

postgres

Let’s check to ensure it’s running:

# docker ps

db_running

Yay! There it is…
Now let’s inspect the database container and see the container’s ip address:

# docker inspect database |grep IPAddress

db_ip

As you can see, the database container’s ip address is 172.17.0.10.

Now let’s spin up another container, this time a make believe web-service container running on uBuntu and enter into a bash shell within that container. We will link the web-service container to the database container with the ‘–link’ argument of docker:

# docker run -it --name webservice --link database:db ubuntu:14.04 bash

ubuntu_con

As you can see, I now have a bash shell prompt inside the ‘web-service’ container.

If we check the /etc/hosts file inside the web-service container, we’ll see an entry to the postgres database container. This was automatically added because we used the ‘–link’ argument when we spun up the web-service container.

# cat /etc/hosts

etc_hosts

Please notice the last entry in the /etc/hosts file. You’ll see 172.17.0.10, the database container ip address – cool! This entry will allow the web-services container to communicate with the database container.

The ‘db’ to the right of the database container’s ip address is the alias we assigned in the ‘–link database:db’ argument when we ran the web-service container. ‘database‘ is the our docker name of the postgres container and ‘db‘ is the local alias name we assigned.

Let’s check out the web-service container’s ip address is:

# ifconfig -a |grep inet

web_ip

You’ll notice the web-service container ip address is 172.17.0.12.

OK, let’s try to ping the database container from the web-services container:

# ping 172.17.0.10

ping

As you can see, the web-services container can see the database container!

Hooray, they can see each other!

The web-service container will be able to access the database container.

Eureka!

Leave a Reply

Your email address will not be published. Required fields are marked *