正如标题所示,我需要能够检索docker托管的IP地址以及从主机到容器的portmap,并在容器内部完成这些工作。


当前回答

在终端上使用hostname -I命令

其他回答

在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'/.$//'`

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

run --env <key>=<value>

所以…如果你使用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/

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.04 bash -c "apt-get update > /dev/null && apt-get install iproute2 -y > /dev/null && ip -4 route show default | cut -d' ' -f3"

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

适用于Mac的Docker, Windows的Docker,以及其他平台。

这是mac专用docker.for.mac的更新。Localhost(17.06版后可用)和docker.for.mac.host.internal(17.12版后可用),它们也可以在该平台上运行。

注意,在Mac和Windows文档中,这仅用于开发目的。

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

MONGO_SERVER=host.docker.internal

在我码头式的写作中。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