docker - 为什么在 Docker 中需要 "--expose"选项?

标签 docker

我对 Docker 中的“--expose”选项感到困惑,我不知道它实际上会做什么。

当我在“docker run ...”中指定它(例如,--expose=1234)时,端口将在哪里暴露?我不认为我可以访问主机中的端口,如果我想要那个,我想我需要的是“-p”,那么“--expose”实际上会做什么?

我想如果我想从主机访问一个容器端口,我需要的是,让容器中的服务监听端口,使用“docker run”中的“-p”选项将端口发布到主持人。或者在这种情况下,我仍然必须使用“--expose”来暴露端口?

最佳答案

-p 将允许您映射一个已经公开的端口(在 Dockerfile 中设置)。

但如果该端口未在 Dockerfile 及其生成的镜像中公开,您仍然可以使用 --expose 公开它:

来自 docker run :

The EXPOSE instruction defines the initial incoming ports that provide services. These ports are available to processes inside the container. An operator can use the --expose option to add to the exposed ports.

这是一种通过在运行时公开该端口来覆盖图像定义(未公开端口)的方法。
实际上“覆盖”是错误的术语,如 PR 14625 中所述和 PR 15675 :

With the exception of the EXPOSE directive, an image developer hasn't got much control over networking. The EXPOSE instruction defines the initial incoming ports that provide services. These ports are available processes inside the container.
An operator can use the --expose option to add to the exposed ports.

(“添加”是这里的关键:您可以在运行时声明其他端口)

正如我在评论中提到的,这与 EXPOSE 端口上的事件无关(它不能保证进程正在监听容器内的端口)
这只是声明 open port 的一种方式,这是一个将接受数据包的端口。

关于docker - 为什么在 Docker 中需要 "--expose"选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35671371/

相关文章:

docker - 如何使用docker-compose为容器设置固定IP地址?

php - docker 和 PHP : getting dependencies (composer) into the container

docker - 使用Docker在分布式模式下运行 Karate 测试

docker - 如何以用户 "nobody?"在临时容器中运行我的 Go 应用程序

Golang 与 docker 的连续工作流程

docker - 连接 : Error while fetching server API version: Ansible 时出错

macos - 在 OSX 上将卷挂载到 Docker 镜像

docker - 在 Docker 中以自定义用户身份运行 ASP.NET Core 应用程序

docker - 如何在容器内查找/访问/var/log/jasmin

docker - 如何在特定时间每天运行容器