简体   繁体   English

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

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

I have a python program which is running inside the docker container on Amazon EC2 instance.我有一个 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. 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. It is easy to get the private IP of the machine using python's socket library, like使用python的socket库很容易得到机器的私有IP,比如

socker.gethostbyname(socket.gethostname())

but it doesn't give the EC2 instance's IP.但它没有给出 EC2 实例的 IP。 Is anyone having any idea how to do it?有人知道怎么做吗?

To know the IP of the host machine you can do the below inside the docker container.要了解主机的 IP,您可以在 docker 容器内执行以下操作。

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

In python, you can probably use subprocess module to get the result.在 python 中,您可能可以使用subprocess模块来获取结果。
https://docs.python.org/3/library/subprocess.html https://docs.python.org/3/library/subprocess.html

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

It won't be possible to get host IP from a container if you are using overlay network or external.如果您使用覆盖网络或外部网络,则无法从容器中获取主机 IP。 It is possible to get IP of the EC2 instance from the host by running curl http://169.254.169.254/latest/meta-data/local-ipv4可以通过运行curl http://169.254.169.254/latest/meta-data/local-ipv4

Pass this as an environment variable when you start the container.启动容器时将其作为环境变量传递。 For eg.例如。 docker run -e HOSTIP=$(http://169.254.169.254/latest/meta-data/local-ipv4)

or in your compose file:或在您的撰写文件中:

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