简单来说:
EXPOSE
是一种文档表述方法--publish
(or -p) 是一种映射host port到container port的方法
EXPOSE只是一种文档表述方式,在dockerfile中让开发者可以更快读懂Image开放了哪些服务,没有实际作用意义。如果没有EXPOSE端口, Container之间服务也是可以互相访问的。
Publish是在docker run
发挥作用,是运行阶段,没有Publish,Host和用户机器就不可以访问Docker内部Container的服务。
在docker 18.03.1-ce版本上验证过,一些非常旧的版本可能有些许差异。
Exposing and publishing ports
In Docker networking, there are two different mechanisms that directly involve network ports: exposing and publishing ports. This applies to the default bridge network and user-defined bridge networks.
You expose ports using the EXPOSE keyword in the Dockerfile or the --expose flag to docker run. Exposing ports is a way of documenting which ports are used, but does not actually map or open any ports. Exposing ports is optional.
You publish ports using the --publish or --publish-all flag to docker run. This tells Docker which ports to open on the container’s network interface. When a port is published, it is mapped to an available high-order port (higher than 30000) on the host machine, unless you specify the port to map to on the host machine at runtime. You cannot specify the port to map to on the host machine when you build the image (in the Dockerfile), because there is no way to guarantee that the port will be available on the host machine where you run the image.
from: Docker container networking
EXPOSE
The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published.
from: Dockerfile reference
参考 What is the difference between “expose” and “publish” in Docker?