如何从 docker 容器内获取 docker 主机的 IP 地址

发布于 2025-01-11 06:59:19 字数 64 浏览 2 评论 0 原文

正如标题所述,我需要能够检索 docker 主机的 IP 地址以及从主机到容器的端口映射,并在容器内部执行此操作。

As the title says, I need to be able to retrieve the IP address the docker hosts and the portmaps from the host to the container, and doing that inside of the container.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(28

如梦初醒的夏天 2025-01-18 06:59:19
/sbin/ip route|awk '/default/ { print $3 }'

正如 @MichaelNeale 所注意到的,在 Dockerfile 中使用此方法是没有意义的(除非我们仅在构建期间需要此 IP),因为此 IP 将在构建期间进行硬编码。

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

As @MichaelNeale noticed, there is no sense to use this method in Dockerfile (except when we need this IP during build time only), because this IP will be hardcoded during build time.

一萌ing 2025-01-18 06:59:19

从版本 18.03 开始​​,您可以使用 host.docker.internal 作为主机的 IP。

适用于 Docker for MacDocker for Windows,也许还有其他平台。

这是 Mac 特定的 docker.for.mac.localhost(自版本 17.06 起可用)和 docker.for.mac.host.internal(自版本 17.06 起可用)的更新17.12,它可能仍然可以在该平台上运行。

请注意,如 MacWindows 文档,仅用于开发目的。

例如,我在主机上设置了环境变量:

MONGO_SERVER=host.docker.internal

在我的 docker-compose.yml 文件中,我有以下内容:

version: '3'

services:
  api:
    build: ./api
    volumes:
      - ./api:/usr/src/app:ro
    ports:
      - "8000"
    environment:
      - MONGO_SERVER
    command: /usr/local/bin/gunicorn -c /usr/src/app/gunicorn_config.py -w 1 -b :8000 wsgi

As of version 18.03, you can use host.docker.internal as the host's IP.

Works in Docker for Mac, Docker for Windows, and perhaps other platforms as well.

This is an update from the Mac-specific docker.for.mac.localhost, available since version 17.06, and docker.for.mac.host.internal, available since version 17.12, which may also still work on that platform.

Note, as in the Mac and Windows documentation, this is for development purposes only.

For example, I have environment variables set on my host:

MONGO_SERVER=host.docker.internal

In my docker-compose.yml file, I have this:

version: '3'

services:
  api:
    build: ./api
    volumes:
      - ./api:/usr/src/app:ro
    ports:
      - "8000"
    environment:
      - MONGO_SERVER
    command: /usr/local/bin/gunicorn -c /usr/src/app/gunicorn_config.py -w 1 -b :8000 wsgi
阳光①夏 2025-01-18 06:59:19

更新:在 Docker for Mac 上,从版本 18.03 开始​​,您可以使用 host.docker.internal 作为主机的 IP。请参阅aljabear 的回答。对于 Docker for Mac 的早期版本,以下答案可能仍然有用:

在 Docker for Mac 上,docker0 桥不存在,因此此处的其他答案可能不起作用。然而,所有传出流量都通过您的父主机路由,因此只要您尝试连接到它识别为自身的 IP(并且 docker 容器不认为是其自身),您就应该能够连接。例如,如果您从父计算机运行:

ipconfig getifaddr en0

这应该会显示 Mac 在当前网络上的 IP,并且您的 docker 容器也应该能够连接到该地址。如果此 IP 地址发生变化,这当然会很痛苦,但是您可以通过在父计算机上执行以下操作,向您的 Mac 添加一个容器认为不是其本身的自定义环回 IP:

sudo ifconfig lo0 alias 192.168.46.49

然后您可以从以下位置测试连接:在带有 telnet 的 docker 容器内。就我而言,我想连接到远程 xdebug 服务器:

telnet 192.168.46.49 9000

现在,当流量进入您的 Mac(地址为 192.168.46.49)时(并且离开容器的所有流量都经过您的 Mac),您的 Mac 将假定 IP 是它本身。当您使用完此 IP 后,您可以像这样删除环回别名:

sudo ifconfig lo0 -alias 192.168.46.49

需要注意的一件事是,如果 docker 容器认为流量的目的地是其自身,则它不会将流量发送到父主机。因此,如果遇到问题,请检查容器内的环回接口:

sudo ip addr show lo

在我的例子中,这显示了 inet 127.0.0.1/8 这意味着我无法使用 127.*< 中的任何 IP /代码> 范围。这就是我在上面的示例中使用 192.168.* 的原因。确保您使用的 IP 不会与您自己的网络上的某些内容冲突。

Update: On Docker for Mac, as of version 18.03, you can use host.docker.internal as the host's IP. See aljabear's answer. For prior versions of Docker for Mac the following answer may still be useful:

On Docker for Mac the docker0 bridge does not exist, so other answers here may not work. All outgoing traffic however, is routed through your parent host, so as long as you try to connect to an IP it recognizes as itself (and the docker container doesn't think is itself) you should be able to connect. For example if you run this from the parent machine run:

ipconfig getifaddr en0

This should show you the IP of your Mac on its current network and your docker container should be able to connect to this address as well. This is of course a pain if this IP address ever changes, but you can add a custom loopback IP to your Mac that the container doesn't think is itself by doing something like this on the parent machine:

sudo ifconfig lo0 alias 192.168.46.49

You can then test the connection from within the docker container with telnet. In my case I wanted to connect to a remote xdebug server:

telnet 192.168.46.49 9000

Now when traffic comes into your Mac addressed for 192.168.46.49 (and all the traffic leaving your container does go through your Mac) your Mac will assume that IP is itself. When you are finish using this IP, you can remove the loopback alias like this:

sudo ifconfig lo0 -alias 192.168.46.49

One thing to be careful about is that the docker container won't send traffic to the parent host if it thinks the traffic's destination is itself. So check the loopback interface inside the container if you have trouble:

sudo ip addr show lo

In my case, this showed inet 127.0.0.1/8 which means I couldn't use any IPs in the 127.* range. That's why I used 192.168.* in the example above. Make sure the IP you use doesn't conflict with something on your own network.

摇划花蜜的午后 2025-01-18 06:59:19

AFAIK,在 Docker for Linux(标准发行版)的情况下,主机的 IP 地址将始终为 172.17.0.1 (在 docker 的主网络上,请参阅注释了解更多)。

获取它的最简单方法是从主机通过 ifconfig (接口 docker0):

ifconfig

从 docker 内部,从 docker 执行以下命令:ip -4 route show default | cut -d" " -f3

您可以使用以下命令行在 docker 中快速运行它:

# 1. Run an ubuntu docker
# 2. Updates dependencies (quietly)
# 3. Install ip package   (quietly)
# 4. Shows (nicely) the ip of the host
# 5. Removes the docker (thanks to `--rm` arg)
docker run -it --rm ubuntu:22.10 bash -c "apt-get update > /dev/null && apt-get install iproute2 -y > /dev/null 2> /dev/null && ip -4 route show default | cut -d' ' -f3"

AFAIK, in the case of Docker for Linux (standard distribution), the IP address of the host will always be 172.17.0.1 (on the main network of docker, see comments to learn more).

The easiest way to get it is via ifconfig (interface docker0) from the host:

ifconfig

From inside a docker, the following command from a docker: ip -4 route show default | cut -d" " -f3

You can run it quickly in a docker with the following command line:

# 1. Run an ubuntu docker
# 2. Updates dependencies (quietly)
# 3. Install ip package   (quietly)
# 4. Shows (nicely) the ip of the host
# 5. Removes the docker (thanks to `--rm` arg)
docker run -it --rm ubuntu:22.10 bash -c "apt-get update > /dev/null && apt-get install iproute2 -y > /dev/null 2> /dev/null && ip -4 route show default | cut -d' ' -f3"
当梦初醒 2025-01-18 06:59:19

对于在 AWS 中运行 Docker 的用户,实例元数据仍然可以从容器内部获得。

curl http://169.254.169.254/latest/meta-data/local-ipv4

例如:

$ docker run alpine /bin/sh -c "apk update ; apk add curl ; curl -s http://169.254.169.254/latest/meta-data/local-ipv4 ; echo"
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/community/x86_64/APKINDEX.tar.gz
v3.3.1-119-gb247c0a [http://dl-cdn.alpinelinux.org/alpine/v3.3/main]
v3.3.1-59-g48b0368 [http://dl-cdn.alpinelinux.org/alpine/v3.3/community]
OK: 5855 distinct packages available
(1/4) Installing openssl (1.0.2g-r0)
(2/4) Installing ca-certificates (20160104-r2)
(3/4) Installing libssh2 (1.6.0-r1)
(4/4) Installing curl (7.47.0-r0)
Executing busybox-1.24.1-r7.trigger
Executing ca-certificates-20160104-r2.trigger
OK: 7 MiB in 15 packages
172.31.27.238

$ ifconfig eth0 | grep -oP 'inet addr:\K\S+'
172.31.27.238

For those running Docker in AWS, the instance meta-data for the host is still available from inside the container.

curl http://169.254.169.254/latest/meta-data/local-ipv4

For example:

$ docker run alpine /bin/sh -c "apk update ; apk add curl ; curl -s http://169.254.169.254/latest/meta-data/local-ipv4 ; echo"
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/community/x86_64/APKINDEX.tar.gz
v3.3.1-119-gb247c0a [http://dl-cdn.alpinelinux.org/alpine/v3.3/main]
v3.3.1-59-g48b0368 [http://dl-cdn.alpinelinux.org/alpine/v3.3/community]
OK: 5855 distinct packages available
(1/4) Installing openssl (1.0.2g-r0)
(2/4) Installing ca-certificates (20160104-r2)
(3/4) Installing libssh2 (1.6.0-r1)
(4/4) Installing curl (7.47.0-r0)
Executing busybox-1.24.1-r7.trigger
Executing ca-certificates-20160104-r2.trigger
OK: 7 MiB in 15 packages
172.31.27.238

$ ifconfig eth0 | grep -oP 'inet addr:\K\S+'
172.31.27.238
泪之魂 2025-01-18 06:59:19
docker network inspect bridge -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}'

可以使用 docker 网络检查 来检索它

docker network inspect bridge -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}'

It's possible to retrieve it using docker network inspect

攒一口袋星星 2025-01-18 06:59:19

唯一的方法是在创建容器时将主机信息作为环境传递

run --env <key>=<value>

The only way is passing the host information as environment when you create a container

run --env <key>=<value>
如若梦似彩虹 2025-01-18 06:59:19

--add-host 可能是一个更干净的解决方案(但没有端口部分,只有主机可以用此解决方案处理)。因此,在您的 docker run 命令中,执行以下操作:类似:(

docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print  $3}'` [my container]

来自 https://stackoverflow.com/a/26864854/127400

The --add-host could be a more cleaner solution (but without the port part, only the host can be handled with this solution). So, in your docker run command, do something like:

docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print  $3}'` [my container]

(From https://stackoverflow.com/a/26864854/127400 )

暗藏城府 2025-01-18 06:59:19

大多数希望自动执行此操作的应用程序的标准最佳实践是:您不这样做。相反,您让运行容器的人注入外部主机名/IP 地址作为配置,例如作为环境变量或配置文件。允许用户注入它可以为您提供最便携的设计。

为什么这会如此困难?因为根据设计,容器会将应用程序与主机环境隔离。默认情况下,网络的命名空间仅限于该容器,并且主机的详细信息受到保护,不受容器内运行的进程的影响,而容器内可能不完全受信任。


根据您的具体情况,有不同的选项:

如果您的容器在主机网络上运行,那么您可以直接查看主机上的路由表以查看默认路由。从 这个问题,以下内容对我有用,例如:

ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'

在容器中显示主机网络的示例如下所示:

docker run --rm --net host busybox /bin/sh -c \
  "ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'"

对于当前版本Docker Desktop 中,他们将 DNS 条目注入到嵌入式虚拟机中:

getent hosts host.docker.internal | awk '{print $1}'

在 20.10 版本中,如果您使用额外选项运行容器,则 host.docker.internal 别名也可以在 Linux 上工作:

docker run --add-host host.docker.internal:host-gateway ...

如果您正在运行在云环境中,您可以检查来自云提供商的元数据服务,例如AWS:

curl http://169.254.169.254/latest/meta-data/local-ipv4

如果您想要外部/互联网地址,您可以查询远程服务,例如:

curl ifconfig.co

其中每一个都有限制,并且仅在特定场景下工作。最可移植的选项仍然是使用作为配置注入的 IP 地址来运行容器,例如,这里有一个选项,在主机上运行之前的 ip 命令并将其作为环境变量注入:

export HOST_IP=$(ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p')
docker run --rm -e HOST_IP busybox printenv HOST_IP

The standard best practice for most apps looking to do this automatically is: you don't. Instead you have the person running the container inject an external hostname/ip address as configuration, e.g. as an environment variable or config file. Allowing the user to inject this gives you the most portable design.

Why would this be so difficult? Because containers will, by design, isolate the application from the host environment. The network is namespaced to just that container by default, and details of the host are protected from the process running inside the container which may not be fully trusted.


There are different options depending on your specific situation:

If your container is running with host networking, then you can look at the routing table on the host directly to see the default route out. From this question the following works for me e.g.:

ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'

An example showing this with host networking in a container looks like:

docker run --rm --net host busybox /bin/sh -c \
  "ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'"

For current versions of Docker Desktop, they injected a DNS entry into the embedded VM:

getent hosts host.docker.internal | awk '{print $1}'

With the 20.10 release, the host.docker.internal alias can also work on Linux if you run your containers with an extra option:

docker run --add-host host.docker.internal:host-gateway ...

If you are running in a cloud environment, you can check the metadata service from the cloud provider, e.g. the AWS one:

curl http://169.254.169.254/latest/meta-data/local-ipv4

If you want your external/internet address, you can query a remote service like:

curl ifconfig.co

Each of these have limitations and only work in specific scenarios. The most portable option is still to run your container with the IP address injected as a configuration, e.g. here's an option running the earlier ip command on the host and injecting it as an environment variable:

export HOST_IP=$(ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p')
docker run --rm -e HOST_IP busybox printenv HOST_IP
一曲琵琶半遮面シ 2025-01-18 06:59:19

Mac 和 Windows 的 TLDR

docker run -it --rm alpine nslookup host.docker.internal

... 打印主机的 IP 地址 ...

nslookup: can't resolve '(null)': Name does not resolve

Name:      host.docker.internal
Address 1: 192.168.65.2

详细信息

位于 MacWindows,您可以使用特殊的 DNS 名称 host.docker.internal

主机的 IP 地址正在变化(如果您没有网络访问权限,则没有 IP 地址)。从 18.03 开始​​,我们建议连接到特殊的 DNS 名称 host.docker.internal,该名称解析为主机使用的内部 IP 地址。这是出于开发目的,不适用于 Docker Desktop for Mac 之外的生产环境。

TLDR for Mac and Windows

docker run -it --rm alpine nslookup host.docker.internal

... prints the host's IP address ...

nslookup: can't resolve '(null)': Name does not resolve

Name:      host.docker.internal
Address 1: 192.168.65.2

Details

On Mac and Windows, you can use the special DNS name host.docker.internal.

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.

迷爱 2025-01-18 06:59:19

如果您想要 Windows 上的真实 IP 地址(不是网桥 IP),并且您有 docker 18.03(或更多)最近)执行以下操作:

从映像名称为 nginx 的主机在容器上运行 bash(适用于 Alpine Linux 发行版):

 docker run -it nginx /bin/ash

然后在容器内运行

/ # nslookup host.docker.internal

Name:      host.docker.internal
Address 1: 192.168.65.2

192.168.65.2< /代码> 是主机的 IP - 不是像 spinus 接受的答案中那样的桥接 IP。

我在这里使用 主机。 docker.internal

主机的 IP 地址正在变化(如果您没有网络访问权限,则没有 IP 地址)。从 18.03 开始​​,我们建议连接到特殊的 DNS 名称 host.docker.internal,该名称解析为主机使用的内部 IP 地址。这是出于开发目的,不适用于 Docker for Windows 之外的生产环境。

If you want real IP address (not a bridge IP) on Windows and you have docker 18.03 (or more recent) do the following:

Run bash on container from host where image name is nginx (works on Alpine Linux distribution):

 docker run -it nginx /bin/ash

Then run inside container

/ # nslookup host.docker.internal

Name:      host.docker.internal
Address 1: 192.168.65.2

192.168.65.2 is the host's IP - not the bridge IP like in spinus accepted answer.

I am using here host.docker.internal:

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker for Windows.

冷︶言冷语的世界 2025-01-18 06:59:19

在 Linux 中,您可以运行

HOST_IP=`hostname -I | awk '{print $1}'`

在 macOS 中,您的主机不是 Docker 主机。 Docker 将在 VirtualBox 中安装其主机操作系统。

HOST_IP=`docker run busybox ping -c 1 docker.for.mac.localhost | awk 'FNR==2 {print $4}' | sed s'/.$//'`

In linux you can run

HOST_IP=`hostname -I | awk '{print $1}'`

In macOS your host machine is not the Docker host. Docker will install it's host OS in VirtualBox.

HOST_IP=`docker run busybox ping -c 1 docker.for.mac.localhost | awk 'FNR==2 {print $4}' | sed s'/.$//'`
天赋异禀 2025-01-18 06:59:19

我有 Ubuntu 16.03。对我

docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print  $3}'` [image]

来说工作(生成了错误的IP)

我的工作解决方案是:

docker run --add-host dockerhost:`docker network inspect --format='{{range .IPAM.Config}}{{.Gateway}}{{end}}' bridge` [image]

I have Ubuntu 16.03. For me

docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print  $3}'` [image]

does NOT work (wrong ip was generating)

My working solution was that:

docker run --add-host dockerhost:`docker network inspect --format='{{range .IPAM.Config}}{{.Gateway}}{{end}}' bridge` [image]
小红帽 2025-01-18 06:59:19

Mac 版 Docker
我想从容器连接到主机上的服务

主机具有不断变化的 IP 地址(如果您没有网络访问权限,则没有 IP 地址)。从 18.03 开始​​,我们建议连接到特殊的 DNS 名称 host.docker.internal,该名称解析为主机使用的内部 IP 地址。

该网关也可以通过 gateway.docker.internal 进行访问。
https://docs.docker.com/docker- for-mac/networking/#use-cases-and-workarounds

Docker for Mac
I want to connect from a container to a service on the host

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.

The gateway is also reachable as gateway.docker.internal.
https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds

冧九 2025-01-18 06:59:19

如果您启用了docker远程API(通过-Htcp://0.0.0.0:4243 例如)并知道主机的主机名或 IP 地址,这可以是完成了很多bash。

在我的容器用户的 bashrc 中:

export hostIP=$(ip r | awk '/default/{print $3}')
export containerID=$(awk -F/ '/docker/{print $NF;exit;}' /proc/self/cgroup)
export proxyPort=$(
  curl -s http://$hostIP:4243/containers/$containerID/json |
  node -pe 'JSON.parse(require("fs").readFileSync("/dev/stdin").toString()).NetworkSettings.Ports["DESIRED_PORT/tcp"][0].HostPort'
)

第二行从本地 /proc/self/cgroup 文件中获取容器 ID。

第三行卷出到主机(假设您使用 4243 作为 docker 端口),然后使用节点解析返回的 JSON 以获得 DESIRED_PORT

If you enabled the docker remote API (via -Htcp://0.0.0.0:4243 for instance) and know the host machine's hostname or IP address this can be done with a lot of bash.

Within my container's user's bashrc:

export hostIP=$(ip r | awk '/default/{print $3}')
export containerID=$(awk -F/ '/docker/{print $NF;exit;}' /proc/self/cgroup)
export proxyPort=$(
  curl -s http://$hostIP:4243/containers/$containerID/json |
  node -pe 'JSON.parse(require("fs").readFileSync("/dev/stdin").toString()).NetworkSettings.Ports["DESIRED_PORT/tcp"][0].HostPort'
)

The second line grabs the container ID from your local /proc/self/cgroup file.

Third line curls out to the host machine (assuming you're using 4243 as docker's port) then uses node to parse the returned JSON for the DESIRED_PORT.

北笙凉宸 2025-01-18 06:59:19

我的解决方案:

docker run --net=host

然后在 docker 容器中:

hostname -I | awk '{打印$1}'

My solution:

docker run --net=host

then in docker container:

hostname -I | awk '{print $1}'

一片旧的回忆 2025-01-18 06:59:19

在终端上使用hostname -I命令

use hostname -I command on the terminal

伤感在游骋 2025-01-18 06:59:19

对于在 AWS 中运行 Docker 的人来说,这是另一个选择。此选项避免使用 apk 添加curl 包并节省宝贵的 7mb 空间。使用内置 wget(整体 BusyBox 二进制文件的一部分):

wget -q -O - http://169.254.169.254/latest/meta-data/local-ipv4

Here is another option for those running Docker in AWS. This option avoids having using apk to add the curl package and saves the precious 7mb of space. Use the built-in wget (part of the monolithic BusyBox binary):

wget -q -O - http://169.254.169.254/latest/meta-data/local-ipv4
唯憾梦倾城 2025-01-18 06:59:19

我是这样做的。在这种情况下,它会在 docker 映像中的 /etc/hosts 中添加一个主机条目,将 taurus-host 指向我的本地计算机 IP::

TAURUS_HOST=`ipconfig getifaddr en0`
docker run -it --rm -e MY_ENVIRONMENT='local' --add-host "taurus-host:${TAURUS_HOST}" ...

然后,从 Docker 容器内,脚本可以使用主机名 taurus-host 访问我的本地计算机托管 docker 容器的机器。

Here is how I do it. In this case, it adds a hosts entry into /etc/hosts within the docker image pointing taurus-host to my local machine IP: :

TAURUS_HOST=`ipconfig getifaddr en0`
docker run -it --rm -e MY_ENVIRONMENT='local' --add-host "taurus-host:${TAURUS_HOST}" ...

Then, from within Docker container, script can use host name taurus-host to get out to my local machine which hosts the docker container.

涙—继续流 2025-01-18 06:59:19

所以...如果你使用 Rancher 服务器运行容器,Rancher v1.6(不确定 2.0 是否有这个)容器可以访问 http://rancher-metadata/ ,其中有很多有用的信息。

可以在容器内部找到 IP 地址:
curl http://rancher-metadata/latest/self/host/agent_ip

有关更多详细信息,请参阅:
https://rancher.com/docs/rancher /v1.6/en/rancher-services/metadata-service/

So... if you are running your containers using a Rancher server, Rancher v1.6 (not sure if 2.0 has this) containers have access to http://rancher-metadata/ which has a lot of useful information.

From inside the container the IP address can be found here:
curl http://rancher-metadata/latest/self/host/agent_ip

For more details see:
https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-service/

短暂陪伴 2025-01-18 06:59:19

试试这个:

docker run --rm -i --net=host alpine ifconfig

Try this:

docker run --rm -i --net=host alpine ifconfig
┊风居住的梦幻卍 2025-01-18 06:59:19

这是 Node.js 中的简约实现,适用于在 AWS EC2 实例上运行主机的用户,使用前面提到的 EC2 元数据实例

const cp = require('child_process');
const ec2 = function (callback) {
    const URL = 'http://169.254.169.254/latest/meta-data/local-ipv4';
    // we make it silent and timeout to 1 sec
    const args = [URL, '-s', '--max-time', '1'];
    const opts = {};
    cp.execFile('curl', args, opts, (error, stdout) => {
        if (error) return callback(new Error('ec2 ip error'));
        else return callback(null, stdout);
    })
        .on('error', (error) => callback(new Error('ec2 ip error')));
}//ec2

并用作

ec2(function(err, ip) {
        if(err) console.log(err)
        else console.log(ip);
    })

This is a minimalistic implementation in Node.js for who is running the host on AWS EC2 instances, using the afore mentioned EC2 Metadata instance

const cp = require('child_process');
const ec2 = function (callback) {
    const URL = 'http://169.254.169.254/latest/meta-data/local-ipv4';
    // we make it silent and timeout to 1 sec
    const args = [URL, '-s', '--max-time', '1'];
    const opts = {};
    cp.execFile('curl', args, opts, (error, stdout) => {
        if (error) return callback(new Error('ec2 ip error'));
        else return callback(null, stdout);
    })
        .on('error', (error) => callback(new Error('ec2 ip error')));
}//ec2

and used as

ec2(function(err, ip) {
        if(err) console.log(err)
        else console.log(ip);
    })
琉璃梦幻 2025-01-18 06:59:19

如果在 Service Fabric 群集上运行 Windows 容器,则可以通过环境变量 Fabric_NodeIPOrFQDN 获取主机的 IP 地址。 Service Fabric 环境变量

If you are running a Windows container on a Service Fabric cluster, the host's IP address is available via the environment variable Fabric_NodeIPOrFQDN. Service Fabric environment variables

沙与沫 2025-01-18 06:59:19

也许我创建的容器也很有用 https://github.com/qoomon/docker-host

你可以简单地使用容器名称dns来访问主机系统,例如curl http://dockerhost:9200,所以没必要任何IP地址的麻烦。

Maybe the container I've created is useful as well https://github.com/qoomon/docker-host

You can simply use container name dns to access host system e.g. curl http://dockerhost:9200, so no need to hassle with any IP address.

呢古 2025-01-18 06:59:19

我使用的解决方案是基于一个“服务器”,当它收到http请求时,它会返回Docker主机的外部地址。

在“服务器”上:

1) 启动 jwilder/nginx-proxy

# docker run -d -p <external server port>:80 -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy

2) 启动 ipify 容器

# docker run -e VIRTUAL_HOST=<external server name/address> --detach --name ipify osixia/ipify-api:0.1.0

现在,当容器向服务器发送 http 请求时,例如

# curl http://<external server name/address>:<external server port>

ipify 通过 http 标头“X-Forwarded”返回 Docker 主机的 IP 地址-For”

示例(ipify 服务器的名称为“ipify.example.com”并在端口 80 上运行,docker 主机的 IP 为 10.20.30.40):

# docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy
# docker run -e VIRTUAL_HOST=ipify.example.com --detach --name ipify osixia/ipify-api:0.1.0

在容器内您现在可以调用:

# curl http://ipify.example.com
10.20.30.40

The solution I use is based on a "server" that returns the external address of the Docker host when it receives a http request.

On the "server":

1) Start jwilder/nginx-proxy

# docker run -d -p <external server port>:80 -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy

2) Start ipify container

# docker run -e VIRTUAL_HOST=<external server name/address> --detach --name ipify osixia/ipify-api:0.1.0

Now when a container sends a http request to the server, e.g.

# curl http://<external server name/address>:<external server port>

the IP address of the Docker host is returned by ipify via http header "X-Forwarded-For"

Example (ipify server has name "ipify.example.com" and runs on port 80, docker host has IP 10.20.30.40):

# docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy
# docker run -e VIRTUAL_HOST=ipify.example.com --detach --name ipify osixia/ipify-api:0.1.0

Inside the container you can now call:

# curl http://ipify.example.com
10.20.30.40
聽兲甴掵 2025-01-18 06:59:19

在 Ubuntu 上,hostname 命令可与以下选项一起使用:

  • -i--ip-address 主机名地址
  • -I, --all-ip-addresses 主机的所有地址

例如:

$ hostname -i
172.17.0.2

要分配给变量,可以使用以下一行:

IP=$(hostname -i)

On Ubuntu, hostname command can be used with the following options:

  • -i, --ip-address addresses for the host name
  • -I, --all-ip-addresses all addresses for the host

For example:

$ hostname -i
172.17.0.2

To assign to the variable, the following one-liner can be used:

IP=$(hostname -i)
水水月牙 2025-01-18 06:59:19

另一种方法基于 traceroute ,它在我的 Linux 主机上工作,例如在基于 Alpine 的容器中:

traceroute -n 8.8.8.8 -m 4 -w 1 | awk '$1~/\d/&&$2!~/^172\./{print$2}' | head -1

这需要一些时间,但列出了不以 开头的第一跳 IP 172.如果没有成功响应,请尝试使用-m 4参数增加测试跃点的限制。

Another approach is based on traceroute and it's working on a Linux host for me, e.g. in a container based on Alpine:

traceroute -n 8.8.8.8 -m 4 -w 1 | awk '$1~/\d/&&$2!~/^172\./{print$2}' | head -1

It takes a moment, but lists the first hop's IP that does not start with 172. If there is no successful response, try increasing the limit on the tested hops using -m 4 argument.

软的没边 2025-01-18 06:59:19

使用 https://docs.docker.com/machine/install-machine/

) $ docker-machine ip

b) 获取一台或多台机器的 IP 地址。

  $ docker-machine ip host_name

  $ docker-machine ip host_name1 host_name2

With https://docs.docker.com/machine/install-machine/

a) $ docker-machine ip

b) Get the IP address of one or more machines.

  $ docker-machine ip host_name

  $ docker-machine ip host_name1 host_name2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文