Docker Community Forums

Share and learn in the Docker community.

Add custom entry to hosts file in container running inside other container

What is the best way to ensure a custom ip address is added to all containers created as build agents by a Jenkins server that is in itself running in a Docker container?

I’m setting up Jenkins in a container and will be using a separate container with Docker installed to spin up the various build agents I will be using. Each agent will be building Java projects using Maven and some of the dependencies will be downloaded from a Nexus server running on AWS.

This Nexus server is not registered in any DNS so in order to use it I have added its ip address to my hosts file (when building these projects locally). This can of course also be done in the containers (the agents) that will now build my projects in my Jenkins container. For instance in my Jenkinsfile I can put the following to add the ip of the Nexus server each time the agent it run.

pipeline {
agent {
  docker {
      image 'maven:3.3-jdk-8'
      args '-v /var/jenkins_home/.m2:/root/.m2 --add-host' 

The problem with this approach is that I have to add this ip address to each projects Jenkinsfile. A much better approach (at least I think it is) would be to create a new image based on the maven:3.3-jdk-8 used in the example and in that Dockerfile somehow update the hosts file of the image itself. I’ve found some examples where this is done using CMD to append the additions to the hosts file.

My actual question is if this is the way to go to accomplish this or if there is some other way which is considered better, more of a best practice for these scenarios?