Connecting Docker Host Services to a Docker Container

Dockers are good way to deploy applications with the thoughts of scalability and management; however, there are some instance where a deployed application needs to use a host service such as MySQL.

Using Host Networking

The first way to allow for a docker to use host services is to make the docker share the networking stack with the docker host, aka giving the docker the keys to the kingdom. This is done by adding 
--net="host" option to the docker run command. By using this option any ports opened on the docker container will also be opened on the docker host machine as well.

Using Bridged Networking

The second way to allow a docker to use host services is to inject the docker host bridge adapater into the docker's /etc/hosts file. This means we will be using DNS lookup to connect to the host services. 

For this I will be using a MySQL service running on the host as an example but other services can be substituted.

First we need to update the MySQL configuration file (found in /etc/mysql/my.cnf) to bind the address 0.0.0.0 (bind-address = 0.0.0.0). Once the configuration is updated, restart the MySQL service.

Next we will need to determine the ip address for the bridge, known as docker0. You can find the address by using ifconfig but it should be 172.17.0.1 by default in the current builds of docker.

Once we have the docker0 ip address, we need to run the docker with the --add-host:parent-host:'172.17.0.1' option where parent-host is what you would like to call the docker host's hostname.

With that your docker should now be able to connect to the host MySQL service.

Using Ansible with Bridge Networking

If you are using ansible to deploy your docker, you will need to add the following to your docker ansible task:

etc_host: >
{
   "{{ parent-host }}": "{{ parent-ip }}"
}

When you run the ansible task, make sure to specify the parent-host and parent-ip variables.

Sources:

Comments

Popular posts from this blog

Deployment By Hardware

Upgrading to Grails 3.2.0 from Grails 2.3.7 with Spring Security and Deployment to Tomcat7