Issue
As per my application requirement, I need to get the server IP and the server name from the python program. But my application is resides inside the specific docker container on top of the Ubuntu.
I have tried like the below
import os
os.system("hostname") # to get the hostname
os.system("hostname -i") # to get the host ip
Output:
2496c9ab2f4a172.*.*.*
But it is giving the host name as a it's residing docker containerid and the host_ip as it's private ip address as above. I need the hostname as it is the server name. But when I type these above commands in the terminal I am able to get result what I want.
Solution
You won't be able to get the host system's name this way. To get it, you can either define an environment variable, either in your Dockerfile, or when running your container (-e option). Alternatively, you can mount your host /etc/hostname
file into the container, or copy it...
This is an example run command I use to set the environment variable HOSTNAME to the host's hostname within the container:
docker run -it -e "HOSTNAME=$(cat /etc/hostname)" <image> <cmd>
In python you can then run os.environ["HOSTNAME"]
to get the hostname.
As far as the IP address goes, I use this command to get retrieve it from a running container:
route -n | awk '/UG[ \t]/{print $2}'
You will have to install route to be able to use this command. It is included in the package net-tools. apt-get install net-tools
Answered By - Anis Answer Checked By - Mary Flores (WPSolving Volunteer)