绑定容器端口以托管在Dockerfile中 [英] Bind container port to host inside Dockerfile
问题描述
通常在绑定端口时,我会执行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.
要将Hostport分配给容器,您需要执行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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!