How to make an entry in /etc/hosts when starting a container?

This is a good example for doing something that shouldn’t be done at all with Docker. As you already knew, app user can’t write the hosts file, but even if it could, it doesn’t need to. In old Docker versions that didn’t use buildkit by default, you could write the hosts file during build, but I never needed it. Buildkit uses a different method to build images running (If I remember correclty) runc and the hosts file is not writeable.

What you need is --add-host hostname:ip passed to docker run or extra_hosts in compose.

But why do you want to refer to the container’s IP address using host.docker.internal? That is pointed to the physical host through a proxy in Docker Desktop and you can implement a similar feature on Linux without the Desktop as well:

By the way the hosts file is not actually part of the container’s filesystem. It is mounted into it. You can use docker container inspect to get its path:

docker container inspect CONTAINER_NAME --format '{{ .HostsPath }}'
1 Like