8

I am an infra admin for providing docker images to developers.

I created "A" images and then tell docker run command is

docker run --add-host=a-lic:10.0.0.1 --add-host=b-lic:10.0.0.2 A

every developers request to me, please remove --add-host option because it is long. So I want to edit /etc/hosts file when docker build if possible.

I find out docker build --add-host option newly create from 17.04 but it does not work as my expected.

someone said --add-host option is for only during building image and another said --add-host option will work as below (my thoughts).

docker build --add-host=a-lic:10.0.0.1 -t A .
docker run -it A

And docker's documentation is not sufficient for this.

$ docker build --help
Usage:  docker build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

Options:
      --add-host list           Add a custom host-to-IP mapping (host:ip)

What is the correct??

hokwang
  • 659
  • 2
  • 9
  • 22

2 Answers2

5

It's by design (see https://github.com/moby/moby/issues/34078#issuecomment-314798584 / https://github.com/moby/moby/pull/30383#issuecomment-314797629); the --add-host feature during build is designed to allow overriding a host during build, but not to persist that configuration in the image.

If it would persist in the image;

  • the image would not be portable (i.e., only work in your specific environment)
  • images would be able to spoof DNS (what if an image contained google.com 123.123.123.123 ?)

The person running an image should remain in control over overriding hosts, not the image author; it's a runtime configuration.

Possible solutions For your situation;

  • Run an internal DNS; you can set the default DNS server to use in the daemon; that way every container started will automatically use the configured DNS by default
  • Use docker compose and provide a docker-compose.yml to your developers. The docker compose file allows you to specify all the options that should be used when starting a container, so developers could just docker compose up to start the container with all the options they need to set.
thaJeztah
  • 27,738
  • 9
  • 73
  • 92
0

There is another approach that would work here, if a bit ugly. This is for Windows, you can easily do the same on Linux.

In your docker run pass in an environment variable e.g.

docker run --env HOST_IP_ADDRESS=a-lic:10.0.0.1

Then at the end of your Dockerfile, you have a batch file or script in the CMD that runs your application e.g

CMD [ "app-start.bat" ]

Add the following line to app-start.bat:

echo %HOST_IP_ADDRESS% >> c:\windows\system32\drivers\etc\hosts

You can add multiple of these if required.

TrojanName
  • 4,853
  • 5
  • 29
  • 41