bash 如何在docker容器中获取本地主机IP地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33102813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:43:37  来源:igfitidea点击:

How to get local host IP address in docker container?

bashshelldocker

提问by Pawan Kumar

I am using docker and run using script. I want to change in one of configuration with host machine IP address in docker.

我正在使用 docker 并使用脚本运行。我想在 docker 中更改主机 IP 地址的配置之一。

#!/bin/bash
IP=$(echo `ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print }'|sed   's/addr://'`)
echo Setting xwiki config IP
CONFIG=/xwiki/webapps/xwiki/WEB-INF/xwiki.cfg
sed -i -e "s/^xwiki.authentication.authhost=localhost*/xwiki.authentication.authhost= $IP/"  $CONFIG

/xwiki/start_xwiki.sh -f

/xwiki/start_xwiki.sh -f

I run my docker with following command.

我使用以下命令运行我的 docker。

docker run -t -i $EXPOSE_PORTS $IMAGE "$@"

回答by VonC

As mentioned in "How to get the ip address of the docker host from inside a docker container", you can directly access it from the container:

如“如何从docker容器内部获取docker主机的ip地址”中提到的,可以直接从容器中访问:

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

But, as commented, when you are using the docker bridge (default) for the containers, this will output the bridges IP like 172.17.42.1 rather than the host's IP such as 192.168.1.x (typical of an home NAT)

但是,正如评论的那样,当您为容器使用 docker 网桥(默认)时,这将输出网桥 IP,如 172.17.42.1 而不是主机的 IP,如 192.168.1.x(典型的家庭 NAT)

You can pass the actual IP as an environment variable with run --env <key>=<value>

您可以将实际 IP 作为环境变量传递 run --env <key>=<value>

-e "DOCKER_HOST=$(ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+')

(From "Is there an easy way to programmatically extract IP address?")

(来自“有没有一种简单的方法可以以编程方式提取 IP 地址?”)

As the OP Pawan Sharmacomments:

正如OP Pawan Sharma评论的那样

docker0gives host docker ip. I used eth0, it gives my host ip.

docker0给主机 docker ip。我用过eth0,它给了我的主机 ip。

-e "DOCKER_HOST=$(ip -4 addr show eth0| grep -Po 'inet \K[\d.]+')

回答by wununuy

docker run -it --net="host" IMAGE?

docker run -it --net="host" IMAGE?

but I'm not quite sure what you want to achive. Something like a application that should be accessable via host ip?

但我不太确定你想达到什么目的。应该可以通过主机 ip 访问的应用程序之类的东西?