我对 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. TheEXPOSE
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/