What is the difference between “expose” and “publish” in Docker?

后端 未结 6 1239

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

6条回答
  •  后悔当初
    2020-11-22 06:16

    See the official documentation reference: https://docs.docker.com/engine/reference/builder/#expose

    The EXPOSE allow you to define private (container) and public (host) ports to expose at image build time for when the container is running if you run the container with -P.

    $ docker help run
    ...
      -P, --publish-all                    Publish all exposed ports to random ports
    ...
    

    The public port and protocol are optional, if not a public port is specified, a random port will be selected on host by docker to expose the specified container port on Dockerfile.

    A good pratice is do not specify public port, because it limits only one container per host ( a second container will throw a port already in use ).

    You can use -p in docker run to control what public port the exposed container ports will be connectable.

    Anyway, If you do not use EXPOSE (with -P on docker run) nor -p, no ports will be exposed.

    If you always use -p at docker run you do not need EXPOSE but if you use EXPOSE your docker run command may be more simple, EXPOSE can be useful if you don't care what port will be expose on host, or if you are sure of only one container will be loaded.

提交回复
热议问题