I want to make it so that the Docker container I spin up use the same /etc/hosts
settings as on the host machine I run from. Is there a way to do this?
I know there is an --add-host
option with docker run
, but that's not exactly what I want because the host machine's /etc/hosts
file may be different on different machines, so it's not great for me to hardcode exact IP addresses/hosts with --add-host
.
Docker maps the host's /etc/hosts into the container at startup. Hence you can add the static mapping in your host's /etc/hosts, you can add some lines to /etc/hosts from command line for docker run with --add-host="..." , or you can derive a new image with an ENTRYPOINT , that changes the file.
Generally speaking, /etc/hosts file can not be modified before running the docker container. However, current docker has an option “–add-host” which adds host-entries onto /etc/hosts when the container is run.
Docker provides two ways for containers to save files on the host system so that the files are persistent even after the container is shut down. These are Docker volumes and bind mounts. This blog will teach you how to share data between a Docker containerized application and the host computer.
Volumes are stored in a part of the host filesystem which is managed by Docker ( /var/lib/docker/volumes/ on Linux).
Use --network=host
in the docker run
command. This tells Docker to make the container use the host's network stack. You can learn more here.
Add a standard hosts file -
docker run -it ubuntu cat /etc/hosts
Add a mapping for server 'foo' -
docker run -it --add-host foo:10.0.0.3 ubuntu cat /etc/hosts
Add mappings for multiple servers
docker run -it --add-host foo:10.0.0.3 --add-host bar:10.7.3.21 ubuntu cat /etc/hosts
Reference - Docker Now Supports Adding Host Mappings
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With