Windows + Docker + 端口未公开/无法访问

11

问题:

从Windows主机,端口映射/暴露无法正常工作。

容器应用程序无法访问。

curl http://localhost:PORT (127.0.0.1 / 0.0.0.0)
-> Could not get any response

curl http://DOCKER-IP:PORT (127.17.0.1 / 127.17.0.2)
-> Could not get any response

curl http://DOCKER-SUBNET-ADDRESS:PORT (10.0.75.0)
-> Could not get any response

安装:

Windows10 主机系统 + Docker 容器 (包含一个简单的 helloworld python flask 应用)

Docker 容器正在运行。 在 Docker 容器内,flask 应用程序表现如预期。

复现:

  1. 获取 hello world 代码库

    git clone https://github.com/shekhargulati/python-flask-docker-hello-world

  2. 构建并运行 Docker 容器

    docker build -t simple-flask-app:latest . docker run -d -p 5000:5000 simple-flask-app --name simple-flask-app

  3. 进入容器并检查 Flask 是否正在运行

    docker exec -it simple-flask-app apt-get install curl curl http://127.0.0.1:5000

    -> 看到 200 OK + Flask is running(或类似文本)

  4. 退出 Docker 容器

    exit

  5. 在 Windows 主机上使用 curl

    curl http://127.0.0.1:5000

    -> 看到 Could not get any response(或类似文本)

6个回答

16

您需要将应用程序设置为在主机上运行='0.0.0.0'。也就是说:

app.run(host='0.0.0.0')

所以当您运行:

> docker run -d -p 5000:5000 simple-flask-app --name simple-flask-app
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat

然后,curl http://localhost:5000可以正常工作。

感谢: https://codefresh.io/docker-tutorial/hello-whale-getting-started-docker-flask/


4
这个!经过无数次搜索和尝试修复、重新安装、更改路由、使用直接 IP 尝试……这就是解决方案,而且没有人在任何地方提到过它…… - wintercounter
终于成功了!在我的情况下,我是通过在Docker容器中使用“vue-cli-service serve --host 0.0.0.0”来启动我的应用程序的。 - Liebster Kamerad

9

我只是改变了名称参数的顺序,就使其在Linux上工作了。

docker run -d -p 5000:5000 --name simple-flask-app simple-flask-app

2
这对我解决了问题。我在末尾加了 -p xxxx:xxxx。 - Bertus van Zyl
这到底为什么会有区别啊! - eddiewould
这是有区别的,因为容器名称将Docker参数与容器参数分开;容器名称之前的所有内容都是Docker参数,容器名称之后的所有内容都是容器参数。 - undefined

9

是的,运行 docker-machine ip 命令,然后使用提供的 IP 地址代替 localhost: http://<docker-machine ip>:<exposed port> - klapshin

2

简短解决方案

  1. 运行您的Docker应用程序 1.1(进入您的Docker并确保您的应用程序按预期工作)
  2. 在您的Windows主机上

    ipconfig

  3. 其中一个公开的IPv4地址将起作用。一个一个尝试。

    curl http://IPCONFIG-IPv4-TRY-OUT:PORT -> 200 OK + Flask is running

-> Windows上的Docker不会像Linux / Mac那样将流量转发到Docker容器。

-> 看起来流量被转发到eth0。


1

您需要连接到实际运行Docker的VM:

通过运行docker-machine ip default找到IP地址并使用该IP地址进行连接:

curl http://<ip-address>:5000

0

与Flask无关,但我最近遇到了同样的问题。我们的主机需要一个静态IP地址,因此我们的IT进行了一些网络配置更改。然后我注意到在控制面板\网络和Internet\网络连接中,vEthernet适配器已被禁用。启用此端口转发到容器实例后,似乎又能正常工作了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接