Search code examples
dockernetworkingdockerfileports

Difference between listening on ports and making them accessible


I'm actually reading through the Docker documentation for the Dockerfile. There is a part where you define how your ports in the container are exposed. While reading that description I found out I have a problem understanding a particular difference here.

from: https://docs.docker.com/engine/reference/builder/#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.

What is the difference between a container (or server application) listening to a port and making it accessible?

If the application is listening to a port - I can for example launch a HTTP Request on it and it will answer me, right? Isn't that some kind of access I have to it as a host (which defined the outside context here)?


Solution

  • The documentation is a bit confusing.

    With the default bridge network, all containers running on a host and the host itself all have access to each other (i.e all ports) through their internal (bridge) ip addresses (Unless of course a firewall on the host or containers is configured to prevent access). This behavior is independent of any EXPOSE, -p and -P options.

    Since the default bridge network is internal to a host, other hosts on your external network will not be able to reach your containers via the internal network. This is where the -p and -P options comes in by exposing a port on your host's external interface(s) that is forwarded to a container.

    The -p option requires that you specify the container port to forward to, but specifying the host port is optional (Host ports will be randomly selected if not specified).

    The -P relies on EXPOSED ports to automatically setup port forwarding to a container's listening ports. Host ports are automatically selected.