简体   繁体   English

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

[英]How to get local host IP address in docker container?

I am using docker and run using script. 我正在使用docker并使用脚本运行。 I want to change in one of configuration with host machine IP address in docker. 我想在docker中使用主机IP地址更改其中一个配置。

#!/bin/bash
IP=$(echo `ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|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 "$@"

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 $3 }'

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 bridge(默认)作为容器时,这将输出桥接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> 您可以使用run --env <key>=<value>将实际IP作为环境变量传递

-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 Sharma comments : 正如OP Pawan Sharma 评论

docker0 gives host docker ip. docker0给主机docker0 ip。 I used eth0 , it gives my host ip. 我使用eth0 ,它给我的主机ip。

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

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访问?

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

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