Browse topics

Publishing ports

Version
29
Review
Draft

Summary#

With the bridge driver's default nat mode and default routing settings, --publish maps a host address and port to a container port. Use 127.0.0.1 to make the published host port reachable only from the Docker host. Leave the host port empty between the colons to have Docker choose one.

Syntax#

sh
docker run --publish 127.0.0.1:8080:80 IMAGE
docker run --publish 127.0.0.1::80 IMAGE
docker run --publish-all IMAGE
docker port CONTAINER 80/tcp

Example#

Run the example on a local daemon with the default bridge settings. It uses a local busybox:1 image. Set BUSYBOX_IMAGE if you have that image under a different tag.

sh
(
  set -eu
  name="dlr-p1-docker-commands-port-$$"

  container=$(docker create --pull never --name "$name" --publish 127.0.0.1::8080 \
    "${BUSYBOX_IMAGE:-busybox:1}" httpd -f -p 8080)
  trap 'docker rm -f "$container" >/dev/null 2>&1 || true' EXIT
  docker start "$container" >/dev/null

  mapping=$(docker port "$container" 8080/tcp)
  echo "host address: ${mapping%:*}"
  case ${mapping##*:} in
    '' | *[!0-9]*) echo "no host port" ;;
    *) echo "host port assigned" ;;
  esac
  docker inspect --format \
    '{{range $port, $bindings := .NetworkSettings.Ports}}{{$port}} bound on {{(index $bindings 0).HostIp}}{{end}}' \
    "$container"
)

Expected output#

Text
host address: 127.0.0.1
host port assigned
8080/tcp bound on 127.0.0.1

The assigned host port can vary. The output shows the bind address and confirms that Docker assigned a numeric port.

Common mistakes#

-p 8080:80 listens on all host addresses unless the daemon or network was configured otherwise, which can expose the service to other machines. EXPOSE in a Dockerfile supplies port metadata for --publish-all. EXPOSE alone leaves the port unpublished.

In routed mode, the host address only selects IPv4 or IPv6, even if it is 127.0.0.1 or ::1. Docker ignores the host port. Clients with a route to the container can reach its published port directly, subject to firewall rules.

Version applicability#

Checked with Docker Engine 29. In releases older than 28.0.0, hosts on the same layer 2 network segment could reach ports published to localhost.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0