Search code examples
dockerhostssbt-native-packager

sbt-native-packager docker: How to add entry in /etc/hosts


I'm using the docker plugin of sbt-native-packager to build a Docker image. I would like my image to have an additional entry in /etc/hosts.

I've tried the following:

dockerCommands in Docker := dockerCommands.value.flatMap {
  case cmd@Cmd("FROM", _) =>
    List(Cmd("FROM", "anapsix/alpine-java")) ++ List(
      Cmd("ENV", "JAVA_MIN_MEM", "1024m"),
      Cmd("RUN", "echo 8.8.8.8 foo >> /etc/hosts")
    )
}

Unfortunately it doesn't seem to work. When I start a container based on this image, the /etc/hosts does not have the extra entry.

It looks like it's actually writing the file because I tried the following instead:

....
Cmd("RUN", "echo 8.8.8.8 foo >> /etc/hosts; ping -c 4 foo")
....

And I'm getting as output the following:

[info] Step 9/15 : RUN echo 8.8.8.8 foo >> /etc/hosts; ping -c 4 foo
[info]  ---> Running in b6d7ba25f96f
[info] PING foo (8.8.8.8): 56 data bytes
[info] 64 bytes from 8.8.8.8: seq=0 ttl=37 time=5.521 ms
[info] 64 bytes from 8.8.8.8: seq=1 ttl=37 time=3.188 ms
[info] 64 bytes from 8.8.8.8: seq=2 ttl=37 time=6.012 ms
[info] 64 bytes from 8.8.8.8: seq=3 ttl=37 time=4.192 ms

So it looks like the modified /etc/hosts is being overridden!

What is the correct way to do this?


Solution

  • The file /etc/hosts is managed by Docker and cannot be customized as part of building an image.

    As you already figured out, you can add a custom entry using RUN echo 8.8.8.8 foo > /etc/hosts; <some_command_requiring_custom_hosts_file>. But this modification is only available during the execution of this particular RUN command.

    In case you need custom entries when running containers use the --add-host parameter of docker run (see docs).

    In general it is a best practise to not include configuration details in a Docker images. Applying configuration only at the time you are running your containers helps to keep the images portable.