• notice
  • Congratulations on the launch of the Sought Tech site

The docker container adds custom hosts and restarts the loss problem

    Manually modify the hosts in the docker container to add some domain name resolution, but all the hosts are lost after restarting the container. Because the three files /etc/hosts, /etc/resolv.conf, and /etc/hostname in the container do not exist in the mirror, but exist in the /var/lib/docker/containers/ directory of the host , these files will be mounted inside the container in the form of mount when the docker container is restarted. Manual modifications to these files in the container are thus overwritten.

    If it can be solved by specifying DNS, you can add the option --dns=xxxx to specify the dns in the container when starting the container, or you can modify the docker configuration file /etc/docker/daemon.json and add DNS configuration options, this It's the same as modifying the DNS of the mirror. See address: http://www.04007.cn/article/1168.html

To achieve permanent modification and preservation of hosts in the container, there are several methods:

1. Add parameters to the docker startup command.

When docker run runs the container, add the parameter --add-host [domain name]:[IP], and add the host and ip of other servers to be accessed to the /etc/hosts file. The example is as follows:
# Add 1 host to point to
docker run -d -p 80:80 --add-host domain.com: -name demo demo:latest
# Add multiple hosts to point to

docker run -d -p 80:80 --add-host domain.com: --add-host domain2.com: -name demo demo:latest

2. Add a modify hosts command after the docker container startup script

This idea is relatively straightforward and usable.
docker exec <containerId> /bin/sh -c "echo domain.com >> /etc/hosts"


Technical otaku

Sought technology together

Related Topic


Leave a Reply