简体   繁体   English

从 Python 程序的 docker 容器中获取主机名

[英]Get the host name from within the docker container from Python program

As per my application requirement, I need to get the server IP and the server name from the python program.根据我的应用程序要求,我需要从 python 程序中获取服务器 IP 和服务器名称。 But my application is resides inside the specific docker container on top of the Ubuntu.但我的应用程序位于 Ubuntu 之上的特定 docker 容器中。

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.*.*.*输出: 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.但是它给出了主机名作为它驻留的 docker containerid 和 host_ip 作为它的私有 IP 地址,如上所述。 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.但是当我在终端中输入上述这些命令时,我能够得到我想要的结果。

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).要获取它,您可以在 Dockerfile 中或在运行容器时定义环境变量(-e 选项)。 Alternatively, you can mount your host /etc/hostname file into the container, or copy it...或者,您可以将主机/etc/hostname文件挂载到容器中,或复制它...

This is an example run command I use to set the environment variable HOSTNAME to the host's hostname within the container:这是我用来将环境变量 HOSTNAME 设置为容器内主机的主机名的示例运行命令:

docker run -it -e "HOSTNAME=$(cat /etc/hostname)" <image> <cmd>

In python you can then run os.environ["HOSTNAME"] to get the hostname.在 python 中,您可以运行os.environ["HOSTNAME"]来获取主机名。 As far as the IP address goes, I use this command to get retrieve it from a running container:就 IP 地址而言,我使用此命令从正在运行的容器中检索它:

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.它包含在包 net-tools 中。 apt-get install net-tools

An alternative might be the following:替代方案可能如下:

ENV:环境:

NODENAME: '{{.Node.Hostname}}'

This will get you the Hostname of the Node, where the container is running as an environment variable (tested on Docker-Swarm / CoreOs Stable).这将为您提供节点的主机名,其中容器作为环境变量运行(在 Docker-Swarm / CoreOs Stable 上测试)。

you can go for something like this:你可以这样做:

def determine_docker_host_ip_address():
    cmd = "ip route show"
    import subprocess
    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    output, error = process.communicate()
    return str(output).split(' ')[2]
import os

os.uname().nodename

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

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