Docker: Port Mapping

Claire Lee
3 min readFeb 5, 2023

Port mapping enables the connection between a container’s internal port and a host’s external port, making the application within the container accessible from outside. In contrast, EXPOSE only allows internal access to the container’s ports. The mapping between the host and container ports , <Host_PORT>: <Container_PORT>, can be specified through the use of the -p option in the docker run command or defined in the ports section of a docker-compose file.

port mapping summary card
Host and container ports

Host Port

A port that is on the host machine that maps to the container port.

Container Port

A port that is inside a container where an application listens for incoming connections.

Port Mapping

When a request is made to the host port, it is forwarded to the container port. This makes the processes running inside the container reachable from outside.

<Host_PORT>:<Container_PORT>
port mapping

docker run command

The mapping between the host port and container port is specified in the docker run command using the -p option. This option allows you to publish the specified container port and make it accessible from the host machine

docker run -p <Host_PORT>:<Container_PORT> <image>
docker run --publish <Host_PORT>:<Container_PORT> <image>

docker compose ports section

  • map the container port to a randomly available host port
ports:
- <Container_PORT>
  • map the container port to the specified host port
ports:
- <Host_PORT>: <Container_PORT>

Expose Port

The EXPOSE instruction is used to specify the ports that an application inside a Docker container will listen on. However, it does not actually publish the port to the host machine. The exposed ports can only be accessed internally.

EXPOSE

docker run command

docker run --expose <Container_PORT> <image>

Dockerfile

EXPOSE <Container_PORT>

EXPOSE vs. publish

EXPOSE vs. publish

--

--