Docker 容器正在运行,但 localhost 不工作

问题描述 投票:0回答:1

我在 docker 容器内有一个 python Flask 应用程序,我尝试在本地主机上运行。当我运行图像来创建新容器时,我将 Host port 设置为 8000 。所以看起来像 8000:5000

当我运行 docker 容器时,我在终端中看到以下内容:

2024-05-10 09:43:06  * Running on http://127.0.0.1:5000
2024-05-10 09:43:06 Press CTRL+C to quit
2024-05-10 09:43:06  * Restarting with stat
2024-05-10 09:43:06  * Debugger is active!
2024-05-10 09:43:06  * Debugger PIN: 132-936-545
2024-05-10 09:43:06  * Serving Flask app 'app'
2024-05-10 09:43:06  * Debug mode: on

但是,当尝试在浏览器上访问时,我得到无法访问此网站

怎么了?

docker docker-compose
1个回答
0
投票

我认为你错过了一件事。

为了以localhost访问Docker的端口,必须执行“端口转发”。也就是说,你需要连接宿主机的端口和Docker容器的端口。

因此,运行docker容器时必须使用-p选项进行端口转发。

这是运行具有端口转发选项的 Docker 容器的示例。

# -d: background execution
# -p: Map port 80 of the host machine to port 5000 of the container.

$ docker container run -d -p 80:5000 [image_name]

当您运行上述命令时,您将能够通过 http://localhost:80 (或 http://localhost)访问您的 Flask 应用程序。

希望对您有帮助。谢谢你:)

© www.soinside.com 2019 - 2024. All rights reserved.