Before you begin

In this tutorial will 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. Example:

# 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'

# 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
...