Understanding Port Mapping in Docker Compose

Mansi Manhas
Mansi Manhas
Published: December 20, 2023

The short answer

In Docker, a port refers to a communication endpoint between the host and a container through which a containerized application can send and receive data.

In Docker Compose, the ports of a service can be mapped under the ports property as follows:

Bash
version: '3'

services:
  service_name:
    build: .
    ports:
      - "[host:]container[/protocol]"

Where:

  • host specifies the host port or port range. If not specified, it uses any available host port.
  • container specifies the container port or port range.
  • protocol restricts the container ports to specified protocols (tcp or udp). If not specified, it uses any available protocol.

For example:

Bash
version: '3'

services:
  api:
    build: .
    ports:
      - "8000:8000/udp"

In this example, the UDP port 8000 of the host is mapped to the UDP port 8000 of the api service, which means that any requests sent to the host machine on port the 8000 will be forwarded to the port 8000 of the container using the UDP protocol.

Easily retrieve this syntax using Warp AI feature

If you’re using Warp as your terminal, you can easily retrieve this syntax using the Warp AI feature:

Entering docker compose ports in the AI question input will prompt a human-readable step by step guide including code snippets.

Mapping multiple ports at once

In Docker, it often happens that a single service runs more than one application, which requires multiple ports to be mapped in order to function correctly.

To map multiple ports at once, you can use the following syntax:

Bash
ports:
  - "[host:]container[/protocol]"
  - "[host:]container[/protocol]"
  - …

For example:

Bash
version: '3'

services:
  website:
    build: .
    ports:
      - "80:80/tcp"
      - "22:22/tcp"

In this example, the HTTP port 80 of the host is mapped to the port 80 of the container, and the SSH port 22 of the host is mapped to the port 22 of the container, both over the TCP protocol.

Specifying a port range

In Compose, you can use port ranges to specify multiple host ports at once. Docker will then assign the first available host port from the list, followed by the second, and then so on.

To specify a range of host ports, you can use the following syntax:

Bash
"[host_start-host_end:]container[/protocol]"

For example:

Bash
version: '3'

services:
  api:
    build: .
    ports:
      - "8080-8082:8080"

In this example, Docker will assign the first available host port between 8080, 8081, and 8082 to the container port 8080.

Note that similarly, you can also specify port ranges for the container as well.

For example:

Bash
version: '3'

services:
  api:
    build: .
    ports:
      - "8080:8080-8082"

Mapping a container port to any available host port

Mapping a container port to any available host port is useful when you don’t want to manage host ports manually, such as during local development. By default, if you don’t specify a host port, Docker will map the first unassigned port to the service.

For example:

Bash
version: '3'

services:
  api:
    build: .
    ports:
      - "3000"

In this example, the container port 3000 will be mapped to any open and available port on the host.

Binding host ports to a specific IP address

By default, Docker binds the specified host port to all network interfaces (i.e. 0.0.0.0), which allows services to be accessible from any external IP address.

To bind the host ports to a specific network interface, you can the following syntax:

Bash
"[ip_address:host:]container[/protocol]"

For example:

Bash
version: '3'

services:
  api:
    build: .
    ports:
      - "127.0.0.1:8000:8002/udp"

In this example, only the requests originating from the IP address 127.0.0.1, which designates the same machine (or localhost), and sent to the port 8000 of the host over the UDP protocol will be forwarded to the port 8000 of the api service.

Note that to verify which ports are exposed, you can use the docker ps command to list all the active Docker containers and their respective port mappings.

Mapping ports using the long form syntax

Docker Compose supports a long syntax which provides a more detailed way to specify port mappings as compared to the concise aforementioned short syntax.

You can specify port mappings using the long syntax as follows:

Bash
version: '3'

services:
  api:
    build: .
    ports:
      - target: "<container_port>"
        host_ip: <host_ip>
        published: "<published_port>"
        protocol: [udp|tcp]
        mode: host

Where:

  • target specifies the container port or port range.
  • host\_ip specifies the host IP address binding. If not set, the host port will be available for all network interfaces (0.0.0.0).
  • published specifies the host port or port range.
  • The protocol restricts the container ports to specified protocols (tcp or udp). If not specified, it uses any available protocol.
  • The mode with host value specifies that this port configuration is used for publishing a host port on each node. If not set, the mode will use the default value ingress, which is used for load balancing and is not intended for the host port mappings.

For example:

Bash
version: '3'

services:
  api:
    build: .
    ports:
      -  target: "8080"
         host_ip: 127.0.0.1
         published: "8002"
         protocol: tcp
         mode: host
      -  target: "8080"
         host_ip: 127.0.0.1
         published: "8003-8004"
         protocol: tcp
         mode: host

In the above example, two different host port mappings have been specified for the container port 8080.

Mapping ports using environment variables

In Compose, you can dynamically map ports using environment variables and the variable substitution syntax as follows:

Bash
"${VAR:-default}:${VAR:-default}"

Where:

  • ${VAR} refers to the environment variable named VAR.
  • default is an optional fallback value used in case the VAR variable is undefined or empty.

For example:

Bash
version: '3'

services:
  api:
    build: .
    ports:
      - "${HOST_PORT}:${CONTAINER_PORT:-8080}”
  webapp:
    build: webapp
    expose:
      - ${CONTAINER_PORT:-8080}

In this example:

  • The HOST\_PORT environment variable is used to specify the host port value.
  • The CONTAINER\_PORT environment variable is used to specify the service internal and external ports, with a fallback port value of 8080.

When you run the docker-compose up command, the service defined in the Compose file will replace the value of the environment variables.

You can refer to the official documentation to learn how to set environment variables in Docker Compose.

Exposing ports internally with expose

In Docker Compose, the expose property is used to define container ports that are exposed for communicating internally with other containers on the same network, and that are not mapped to the host ports.

Bash
expose:
  - "<ports>"

Where:

  • ports specifies a list of ports or port ranges.

For example:

Bash
version: '3'

services:
  api:
    build: .
    expose:
      - "3000"
      - "8000-8002"
  webapp:
    build: webapp
    expose:
      - "3000"

In this example, the api service exposes the ports 3000, and port range 8000-8002, and the webapp service exposes the port 3000. These ports can be used for communicating with other containers available on the same network, and it is secure as the ports are not exposed externally.

Written by
Mansi Manhas
Mansi Manhas
Filed under

Related articles


Learning Docker (The Easy Way) Using LazyDocker & Warp

A concise guide to learning Docker using Lazydocker. Highlights Docker’s benefits and takes advantage of Warp's AI features for a quick setup.

Run SSH In Docker

Learn how to launch and connect to a containerized SSH server in Docker using password-based authentication and SSH keys.

Remove a Docker Image

Learn how to remove a Docker image locally, on a Docker registry, and on Artifactory.

Override the Container Entrypoint With docker run

Learn how to override and customize the entrypoint of a Docker container using the docker run command.

The Dockerfile ARG Instruction

Learn how to define and set build-time variables for Docker images using the ARG instruction and the --build-arg flag.

Start a Docker Container

Learn how to start a new Docker container from an image in both the foreground and the background using the docker-run command.

Stop All Docker Containers

How to gracefully shutdown running containers and forcefully kill unresponsive containers with signals in Docker using the docker-stop and docker-kill commands.

Set Docker Container Hostname

Learn how to set, change and match a docker container hostname.

How To Use An .env File In Docker Compose

Learn how define and pass environment variables to Docker containers using an .env file in Docker Compose.

Use An .env File In Docker

Learn how to write and use .env files in Docker to populate the environment of containers on startup.

Restart Docker Containers

Learn how to restart Docker containers automatically with restart policies and manually using the docker restart, docker start, docker stop and docker kill commands.

Run Bash Shell In Docker

Start an interactive shell in Docker container