Connect external services from Docker container

Before you begin

In this tutorial, we’ll learn how to connect to different services from the inside of a Docker container. A Linux machine and Docker will be required to follow this tutorial.

Connect to remote services

Make sure you have access to the remote service from the host where containers are running. In this example we are going to use Docker to connect to an external database:

# First check remote access
$ telnet [MYSQL_REMOTE_HOST] [MYSQL_REMOTE_PORT]

# Finally Run the container
$ docker run -it mysql -h [MYSQL_REMOTE_HOST] -P [MYSQL_REMOTE_PORT] -u [MYSQL_REMOTE_USER] --password=[MYSQL_REMOTE_PASSWORD] [MYSQL_REMOTE_DATABASE]

In this post you’ll have examples about how to connect and backing up a remote MySQL database using Docker.

Connect to localhost services

Use the following commands to connect from the inside of the container to localhost running services:

# Get Docker default bridge IP
$ DOCKER_HOST=`/sbin/ifconfig docker0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'`

# Run application
$ docker run -it my_application --add-host 'DOCKER_HOST:$DOCKER_HOST'

Connect to other containerized services

There are two ways to achieve this goal:

1) Link them together using --link. MySQL client-server example:

# Run server
$ docker run --name mysql_server -d -p 3307:3306 -e MYSQL_ROOT_PASSWORD=password mysql

# Run client
$ docker run --rm --name my_client -it --link mysql_server:mysql_server alpine ping mysql_server
>
PING mysql_server (172.17.0.5): 56 data bytes
64 bytes from 172.17.0.5: seq=0 ttl=64 time=0.304 ms
64 bytes from 172.17.0.5: seq=1 ttl=64 time=0.143 ms
...

2) Use a user-defined network (Best practice and recommended option). MySQL client-server example:

$ docker network ls

$ docker network create --driver bridge my_network

# Run server
$ docker run --name mysql_server -d -p 3307:3306 --network my_network -e MYSQL_ROOT_PASSWORD=password mysql

# Run client in a different network raises an error
$ docker run --rm --name my_client -it alpine ping mysql_server
>
ping: bad address 'mysql_server'

<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-layout="in-article"
     data-ad-format="fluid"
     data-ad-client="ca-pub-8396740237415609"
     data-ad-slot="7418246014"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>


# Run client in the same network of the server works well
$ docker run --rm --name my_client -it --network my_network alpine ping mysql_server
>
PING mysql_server (172.22.0.2): 56 data bytes
64 bytes from 172.22.0.2: seq=0 ttl=64 time=0.114 ms
64 bytes from 172.22.0.2: seq=1 ttl=64 time=0.262 ms
...

Finally, you should definitely take a look at these books to fuel your Docker knowledge: