繁体   English   中英

有没有办法从 docker 容器中获取 EC2 实例 ip ?

[英]Is there any way to get the EC2 instance ip from docker container?

我有一个 python 程序在 Amazon EC2 实例上的 docker 容器内运行。 I want to fetch the EC2 instance private IP inside my python program (which is running inside the docker container) without using http://169.254.169.254/latest/meta-data/local-ipv4 this URL. 使用python的socket库很容易得到机器的私有IP,比如

socker.gethostbyname(socket.gethostname())

但它没有给出 EC2 实例的 IP。 有人知道怎么做吗?

要了解主机的 IP,您可以在 docker 容器内执行以下操作。

/sbin/ip route|awk '/default/ { print $3 }'

在 python 中,您可能可以使用subprocess模块来获取结果。
https://docs.python.org/3/library/subprocess.html

类似问题: How to get the IP address of the docker host from inside a docker container

如果您使用覆盖网络或外部网络,则无法从容器中获取主机 IP。 可以通过运行curl http://169.254.169.254/latest/meta-data/local-ipv4

启动容器时将其作为环境变量传递。 例如。 docker run -e HOSTIP=$(http://169.254.169.254/latest/meta-data/local-ipv4)

或在您的撰写文件中:

environment:
  - HOSTIP=${HOSTIP:-`curl http://169.254.169.254/latest/meta-data/local-ipv4`}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM