1

I have a python program which is running inside the docker container on Amazon EC2 instance. 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

socker.gethostbyname(socket.gethostname())

but it doesn't give the EC2 instance's IP. Is anyone having any idea how to do it?

  • Suggesting you to remove the actual IP of the machine to convey the meaning but not cause security issues – hrmnjt Sep 20 '19 at 16:21

2 Answers2

1

It won't be possible to get host IP from a container if you are using overlay network or external. 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

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`}
donnie
  • 2,981
  • 2
  • 16
  • 24
0

To know the IP of the host machine you can do the below inside the docker container.

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

In python, you can probably use subprocess module to get the result.
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

hrmnjt
  • 183
  • 7