How can you make the Docker container use the host machine's '/etc/hosts' file?

后端 未结 11 1765
夕颜
夕颜 2020-12-23 11:21

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

相关标签:
11条回答
  • 2020-12-23 11:39

    If trusted users start your containers, you could use a shell function to easily "copy" the /etc/hosts entries that you need:

    add_host_opt() { awk "/\\<${1}\\>/ {print \"--add-host $1:\" \$1}" /etc/hosts; }
    

    You can then do:

    docker run $(add_host_opt host.name) ubuntu cat /etc/hosts
    

    That way you do not have to hard-code the IP addresses.

    0 讨论(0)
  • 2020-12-23 11:42

    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

    0 讨论(0)
  • 2020-12-23 11:44

    If you are using docker-compose.yml, the corresponding property is:

    services:
      xxx:
        network_mode: "host"
    

    Source

    0 讨论(0)
  • 2020-12-23 11:47

    extra_hosts (in docker-compose.yml)

    https://docs.docker.com/compose/compose-file/

    Add hostname mappings. Use the same values as the docker client --add-host parameter.

    extra_hosts:
     - "somehost:162.242.195.82"
     - "otherhost:50.31.209.229"
    
    0 讨论(0)
  • 2020-12-23 11:49

    Add this to your run command:

    -v /etc/hosts:/etc/hosts
    
    0 讨论(0)
  • 2020-12-23 11:52

    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.

    0 讨论(0)
提交回复
热议问题