问题描述
通常在绑定端口时,我会执行 docker run -p hostport:dockerport ...
,但是我可以在我的 Dockerfile
中指定端口绑定吗?
Normally when binding port, I would do docker run -p hostport:dockerport ...
, but can I specify the port binding inside my Dockerfile
?
我正在启动一个侦听端口的服务器.服务器通过 cmd 行参数获取端口.如果我不必在两个地方(在 docker run
命令和 Dockerfile
中)重复端口,那就太好了
I'm starting a server that listens on a port. The server takes the port through cmd line arguments. It would be great if I don't have to repeat the port in two places (in docker run
command and in Dockerfile
)
推荐答案
在dockerfile
中你只能使用expose
.EXPOSE
指令通知 Docker 容器在运行时监听指定的网络端口.EXPOSE 不会使主机可以访问容器的端口.
In dockerfile
you can only use expose
. The EXPOSE
instruction informs Docker that the container listens on the specified network ports at runtime. EXPOSE does not make the ports of the container accessible to the host.
要将主机端口分配给容器,您需要执行publish
(-p
).或者 -P
标志发布所有暴露的端口.
To allocate Hostport to container you need to do publish
(-p
). Or the -P
flag to publish all of the exposed ports.
要自动化该过程,您可以使用 docker-compose
.在 docker compose 文件中,您可以使用不同的参数编排多个 docker run
命令.
To automate the process, You can use docker-compose
. In docker compose file you can orchestrate multiple docker run
commands with different arguments.
这篇关于将容器端口绑定到 Dockerfile 内的主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!