How to get the IP address of the docker host from inside a docker container

后端 未结 24 1919
鱼传尺愫
鱼传尺愫 2020-11-22 06:41

As the title says. I need to be able to retrieve the IP address the docker hosts and the portmaps from the host to the container, and doing that inside of the container.

24条回答
  •  醉话见心
    2020-11-22 07:28

    The standard best practice for most apps looking to do this automatically is: you don't. Instead you have the person running the container inject an external hostname/ip address as configuration, e.g. as an environment variable or config file. Allowing the user to inject this gives you the most portable design.

    Why would this be so difficult? Because containers will, by design, isolate the application from the host environment. The network is namespaced to just that container by default, and details of the host are protected from the process running inside the container which may not be fully trusted.


    There are different options depending on your specific situation:

    If your container is running with host networking, then you can look at the routing table on the host directly to see the default route out. From this question the following works for me e.g.:

    ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'
    

    An example showing this with host networking in a container looks like:

    docker run --rm --net host busybox /bin/sh -c \
      "ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'"
    

    For some versions of Docker Desktop, they injected a DNS entry into the embedded VM:

    getent hosts host.docker.internal | awk '{print $1}'
    

    If you are running in a cloud environment, you can check the metadata service from the cloud provider, e.g. the AWS one:

    curl http://169.254.169.254/latest/meta-data/local-ipv4
    

    If you want your external/internet address, you can query a remote service like:

    curl ifconfig.co
    

    Each of these have limitations and only work in specific scenarios. The most portable option is still to run your container with the IP address injected as a configuration, e.g. here's an option running the earlier ip command on the host and injecting it as an environment variable:

    export HOST_IP=$(ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p')
    docker run --rm -e HOST_IP busybox printenv HOST_IP
    

提交回复
热议问题