socket.error:[errno 99] cannot assign requested address : flask and python

socket.error:[errno 99] cannot assign requested address : flask and python

我遇到了与 here and here

相同的问题

我正在尝试 运行 docker 中的烧瓶应用程序 container.It 可以正常使用“0.0.0.0”,但它会抛出我的 IP 地址错误

我在公司代理后面。当我用 ipconfig 检查我的 ip 地址时,它显示 IP 地址为:10.***.**.** 我正在使用 docker 工具箱,其中我的容器 ip 是 172.17.0.2,VM IP 地址是 192.168.99.100.

我有一个 flask 应用程序 运行ning 在这个 docker 中,主机

if __name__ == "__main__":
    app.run(host= '0.0.0.0')

工作正常。但是当我把它改成我的IP地址时

if __name__ == "__main__":
        app.run(host= '10.***.**')

抛出错误:

socket.error:[errno 99] cannot assign requested address

我用一个简单的 flask 应用程序再次检查了 ip 地址,该应用程序在本地 运行ning(即没有 docker)

 if __name__ == "__main__":
            app.run(host= '10.***.**')

它运行良好。

所以只有在 docker 中 运行ning 时才会出现问题。那是因为我在路由器 运行ning NAT 后面,具有内部 IP 地址。我如何通过 NAT 找到这个内部 IP 地址?我已经为端口 5000 的烧瓶应用程序完成了端口转发。

> iptables -t nat -A DOCKER -p tcp --dport 5000 -j DNAT --to-destination 172.17.0.2:5000
> iptables -t nat -A POSTROUTING -j MASQUERADE -p tcp --source 172.17.0.2 --destination 172.17.0.2 --dport https
> iptables -A DOCKER -j ACCEPT -p tcp --destination 172.17.0.2 --dport https

要让 LAN 上的其他计算机连接到您的服务,只需在 app.run() 函数中使用 0.0.0.0 地址,并将 docker 容器中的所需端口公开到您的主机 PC。

要公开端口,您需要

1) 在 Dockerfile

中指定 EXPOSE 指令

2) 运行 带有 -p <port_on_host>:<port_in_container> 参数的容器。

例如:

Docker 文件:

FROM ubuntu:17.10

RUN apt-get update && apt-get install -y apache2

EXPOSE 80

ENTRYPOINT ["/usr/sbin/apache2ctl"]
CMD ["-D", "FOREGROUND"]

建造:

docker build -t image_name .

运行:

docker run -d -p 80:80 image_name

检查:

curl http://localhost

P.S。确保 80 端口在 运行ning 容器之前未被主机上的其他应用程序使用。如果此端口已被使用 - 指定另一个端口,例如 8080:

docker run -d -p 8080:80 image_name

然后检查:

curl http://localhost:8080

文档是 here.

OSError [Errno 99] - python 的答案也适用于此。

如果使用 ip 地址但不使用主机名可以正常工作。

删除 /etc/hosts 中的双本地主机应该是解决方案。主机文件应该看起来像这样(将 ip 映射到主机名)

127.0.0.1   localhost
127.0.1.1   your_hostname_here

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

@'Artsiom Praneuski' 的回答只涉及 Docker 配置,这与 docker 容器设置相关,但不指向 Python 环境修复(两者容器和正常设置)。