Oct 21, 2015

How to add a hostname - ip-address to /etc/hosts inside a docker container

Docker is a container virtualization. This lets you create a image which can be started as a

To let the container communicate, e.g. a appserver like wildfly/tomcat with a database, you can
use the option '--link' to give a local name in the appserver container and the name of the container,
which provides the database.

The locale name of the database container is inserted into the local /etc/hosts and is accessible by
name in the data-source definition of an appserver.

Now I have to access an external WebService with https. The certificate is inserted into a java
keystore and the keystore is configured for the JVM-process. ( appserver )

When using the IP-addresse, there is an exception, that the domainname does not match.
Using the domainname of the external server, then it must be resolveable.

In my case this system is not maintained in a DNS-server and therefore I can't use the
--dns and --dns-search of the docker run command.

The first attempt, to add the hostname/IP during building of the image fails, because docker
constructs the /etc/hosts during startup of the container.

After a little searching in the options of docker run, I found the option --add-host=<host:ip>

Supplying this option during the startup of the container with
docker run --add-host=a.b.com: ......
add's this host to the containers /etc/hosts and can be used in the configuration inside the container.