“暴露”与“暴露”之间有什么区别?和“发布”在Docker中?

问题描述:

我正在试验Dockerfile,我认为我了解大多数逻辑。但是,在这种情况下,我看不到公开和发布端口之间的区别。

I'm experimenting with Dockerfiles, and I think I understand most of the logic. However, I don't see the difference between "exposing" and "publishing" a port in this context.

我首先看到的所有教程都包括 EXPOSE 命令:

All the tutorials I have seen first include the EXPOSE command in the Dockerfile:

...
EXPOSE 8080
...

然后他们从此Dockerfile构建映像:

They then build an image from this Dockerfile:

$ docker build -t an_image - < Dockerfile

然后在运行映像时 publish 与上面相同的端口:

And then publish the same port as above when running the image:

$ docker run -d -p 8080 an_image

或使用以下命令发布所有端口

or publish all ports using

$ docker run -d -P an_image

在Dockerfile中公开端口的意义是什么,如果该端口仍然可以发布的话?是否需要先公开一个端口,然后将其发布?实际上,我想在创建映像时指定要在Dockerfile中使用的所有端口,然后不再打扰它们,只需使用以下命令即可运行它们:

What is the point of exposing a port in the Dockerfile, if it will be published anyway? Would there ever be a need to expose a port first, and not publish it later? Effectively, I would like to specify all the ports that I will use in the Dockerfile when creating the image, and then not bother with them again, running them simply with:

$ docker run -d an_image

这可能吗?

基本上,您有三个选择:

Basically, you have three options:


  1. 既未指定 EXPOSE ,也未指定 -p

  2. 仅指定 EXPOSE

  3. 指定 EXPOSE -p

  1. Neither specify EXPOSE nor -p
  2. Only specify EXPOSE
  3. Specify EXPOSE and -p

1)如果未指定 EXPOSE -p ,只能从容器本身的内部访问容器中的服务。

1) If you specify neither EXPOSE nor -p, the service in the container will only be accessible from inside the container itself.

2)如果您 EXPOSE 端口,则无法从Docker外部访问容器中的服务,而可以从其他Docker容器内部访问容器中的服务。

2) If you EXPOSE a port, the service in the container is not accessible from outside Docker, but from inside other Docker containers. So this is good for inter-container communication.

3)如果您 EXPOSE -p 一个端口,容器中的服务可以从任何地方访问,甚至在Docker外部也可以访问。

3) If you EXPOSE and -p a port, the service in the container is accessible from anywhere, even outside Docker.

两者分开的原因是恕我直言,因为:

The reason why both are separated is IMHO because:


  • 选择主机端口取决于主机,因此不属于Dockerfile(否则取决于主机),

  • ,通常可以从其他容器访问容器中的服务。

文档明确指出:


EXPOSE 指令公开用于链接的端口。

The EXPOSE instruction exposes ports for use within links.

它还为您提供了链接容器的方法。容器间

It also points you to how to link containers, which basically is the inter-container communication I talked about.

PS:如果您执行 -p ,但不要执行 EXPOSE ,Docker进行隐式 EXPOSE 。这是因为如果某个端口向公众开放,那么它也会自动向其他Docker容器开放。因此, -p 包括 EXPOSE 。这就是为什么我没有将其列为第四种情况。

PS: If you do -p, but do not EXPOSE, Docker does an implicit EXPOSE. This is because if a port is open to the public, it is automatically also open to other Docker containers. Hence -p includes EXPOSE. That's why I didn't list it above as a fourth case.