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

后端 未结 24 1773
鱼传尺愫
鱼传尺愫 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:42

    If you enabled the docker remote API (via -Htcp://0.0.0.0:4243 for instance) and know the host machine's hostname or IP address this can be done with a lot of bash.

    Within my container's user's bashrc:

    export hostIP=$(ip r | awk '/default/{print $3}')
    export containerID=$(awk -F/ '/docker/{print $NF;exit;}' /proc/self/cgroup)
    export proxyPort=$(
      curl -s http://$hostIP:4243/containers/$containerID/json |
      node -pe 'JSON.parse(require("fs").readFileSync("/dev/stdin").toString()).NetworkSettings.Ports["DESIRED_PORT/tcp"][0].HostPort'
    )
    

    The second line grabs the container ID from your local /proc/self/cgroup file.

    Third line curls out to the host machine (assuming you're using 4243 as docker's port) then uses node to parse the returned JSON for the DESIRED_PORT.

提交回复
热议问题