You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker部署Flask应用后浏览器无法连接问题求助

Flask容器应用无法访问问题排查与解决

问题背景

已构建Docker镜像并在3000端口运行容器,容器处于运行状态,但浏览器访问时连接被拒绝。

相关配置

index.py

from flask import Flask
#from gevent.pywsgi import WSGIServer

app = Flask(__name__)

@app.route('/api', methods=['GET'])
def index():
    return "Hello, World!"

if __name__ == '__main__':
    app.run(debug=True)

requirements.txt

flask

Dockerfile

FROM python:3.12.0a5-alpine3.17
WORKDIR /app
COPY . /app
RUN pip install --retries 5 -r requirements.txt
EXPOSE 3000
CMD ["python" ,"index.py"]

排查信息

端口映射检查

执行命令 sudo docker port 90da591d332c,输出:

3000/tcp -> 0.0.0.0:3000
3000/tcp -> :::3000

防火墙规则检查

执行命令 sudo iptables -L,输出:

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy DROP)
target     prot opt source               destination
DOCKER-USER  all  --  anywhere             anywhere
DOCKER-ISOLATION-STAGE-1  all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain DOCKER (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             172.17.0.2           tcp dpt:3000

Chain DOCKER-ISOLATION-STAGE-1 (1 references)
target     prot opt source               destination
DOCKER-ISOLATION-STAGE-2  all  --  anywhere             anywhere
RETURN     all  --  anywhere             anywhere

Chain DOCKER-ISOLATION-STAGE-2 (1 references)
target     prot opt source               destination
DROP       all  --  anywhere             anywhere
RETURN     all  --  anywhere             anywhere

Chain DOCKER-USER (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere

浏览器访问报错

浏览器访问报错

已执行sudo iptables -L和sudo lsof -i :<port-number>命令检查防火墙及端口状态。

解决方案

问题根源在于Flask默认监听地址为127.0.0.1,仅允许容器内部访问,外部无法连接。需要修改启动代码,指定监听0.0.0.0和对应端口:

修改index.py中的启动部分:

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3000, debug=True)

重新构建镜像并运行容器后,即可通过浏览器访问http://<主机IP>:3000/api正常获取响应。

内容的提问来源于stack exchange,提问作者Hind Hilali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:53:18