TExcelTAD
Home › Docker Compose › Ports

Ports

Services in a Compose project talk to each other over the project network, by service name, on whatever port the program listens on. No configuration is needed for that. ports is only about the outside world: it publishes a container port on the Docker host, so that your browser, another machine or a load balancer can reach it. This lesson covers the short and long syntax, what Compose turns them into, ranges, protocols, binding to one interface, and the mistakes that bite people in production. (The basics of -p are in the Docker course's Ports lesson.)

text
   browser ──▶ host 127.0.0.1:8080 ──(published)──▶ shop-web-1:80
                                                       │ project network: no ports needed
                                                       ▼
                                                   shop-api-1:8000 ──▶ shop-db-1:5432

Short syntax

The short syntax is a string [HOST_IP:][HOST_PORT:]CONTAINER_PORT[/PROTOCOL]. Always quote it. Compose expands every form into the same canonical structure:

compose · try it yourself
services:
  web:
    image: nginx:1.29
    ports:
      - "8080:80"
      - "127.0.0.1:5432:5432"
      - "3000"
      - "53:53/udp"
      - "9000-9001:9000-9001"
      - "8000-8002:80"
      - "[::1]:6000:6000"
name: demo
services:
  web:
    image: nginx:1.29
    networks:
      default: null
    ports:
      - mode: ingress
        target: 80
        published: "8080"
        protocol: tcp
      - mode: ingress
        host_ip: 127.0.0.1
        target: 5432
        published: "5432"
        protocol: tcp
      - mode: ingress
        target: 3000
        protocol: tcp
      - mode: ingress
        target: 53
        published: "53"
        protocol: udp
      - mode: ingress
        target: 9000
        published: "9000"
        protocol: tcp
      - mode: ingress
        target: 9001
        published: "9001"
        protocol: tcp
      - mode: ingress
        target: 80
        published: 8000-8002
        protocol: tcp
      - mode: ingress
        host_ip: ::1
        target: 6000
        published: "6000"
        protocol: tcp
networks:
  default:
    name: demo_default

Read the output entry by entry:

Short form Canonical result Meaning
"8080:80" published: "8080", target: 80 host port 8080 → container port 80, on all interfaces
"127.0.0.1:5432:5432" host_ip: 127.0.0.1 reachable from this machine only
"3000" no published a random free host port; find it with docker compose port web 3000
"53:53/udp" protocol: udp UDP instead of TCP (the default)
"9000-9001:9000-9001" two entries a range is expanded port by port
"8000-8002:80" published: 8000-8002 one container port, the first free host port in the range
"[::1]:6000:6000" host_ip: ::1 IPv6 address in brackets

target (the container side) is a number, while published is a string, because it may be a range.

Long syntax

The long syntax spells out the fields directly. It is more verbose but has no parsing surprises, and it can do two things the short form can't: give the port a name and an app_protocol, and choose the mode.

compose · try it yourself
services:
  web:
    image: nginx:1.29
    ports:
      - name: web-secure
        target: 443
        published: "8443"
        host_ip: 127.0.0.1
        protocol: tcp
        app_protocol: https
      - target: 80
        published: 8081
        mode: host
WARN[0000] service "web": ports[80/tcp].mode: ports[].mode: host is only honored by the Swarm routing mesh
name: demo
services:
  web:
    image: nginx:1.29
    networks:
      default: null
    ports:
      - name: web-secure
        mode: ingress
        host_ip: 127.0.0.1
        target: 443
        published: "8443"
        protocol: tcp
        app_protocol: https
      - mode: host
        target: 80
        published: "8081"
        protocol: tcp
networks:
  default:
    name: demo_default

mode: ingress (the default) and mode: host matter in Swarm: ingress uses the routing mesh across all nodes, host binds only on the node running the task. Plain Compose binds on the single host either way, and config warns that mode: host only means something to Swarm. name and app_protocol are metadata for tools; the published number 8081 became the string "8081".

ports vs expose

Key Effect Who can connect
ports publishes on the host anything that can reach the host IP
expose documents a port (like EXPOSE in a Dockerfile); publishes nothing services on the same network, which could connect anyway
neither nothing services on the same network still connect fine

A frequent misconception is that a database needs ports so the API can reach it. It doesn't: db:5432 works on the project network. Publishing it only exposes your database to the outside.

Invalid ports are caught early

config checks port syntax and ranges:

compose · try it yourself
services:
  web:
    image: nginx:1.29
    ports:
      - "70000:80"
invalid hostPort: 70000
compose · try it yourself
services:
  web:
    image: nginx:1.29
    ports:
      - "9000-9001:80-82"
invalid ranges specified for container and host Ports: 80-82 and 9000-9001

A range on both sides must have the same length. Conflicts between services are not caught by config, though: two services may both ask for 8080, and the second one only fails when up tries to bind it:

text
$ docker compose up -d
[+] Running 3/4
 ✔ Network demo_default   Created                                          0.1s
 ✔ Container demo-web-1   Started                                          0.4s
 ⠿ Container demo-web2-1  Starting                                         0.5s
Error response from daemon: failed to set up container networking: driver failed programming external
connectivity on endpoint demo-web2-1: Bind for 0.0.0.0:8080 failed: port is already allocated

(Sample output.) The model below does what up does: walk the services and allocate host ports, reporting conflicts and resolving ranges and random ports.

python · try it yourself
def allocate(services, taken):
    used = set(taken)
    next_random = 32768
    for service, specs in services.items():
        for spec in specs:
            host, container = spec.split(":") if ":" in spec else (None, spec)
            if host is None:
                while next_random in used:
                    next_random += 1
                port = next_random
            elif "-" in host:
                lo, hi = map(int, host.split("-"))
                free = [p for p in range(lo, hi + 1) if p not in used]
                if not free:
                    print(f"{service:8} {spec:14} error: no free port in {host}")
                    continue
                port = free[0]
            else:
                port = int(host)
                if port in used:
                    print(f"{service:8} {spec:14} error: port {port} is already allocated")
                    continue
            used.add(port)
            print(f"{service:8} {spec:14} 0.0.0.0:{port} -> {container}/tcp")

allocate({
    "web": ["8080:80"],
    "admin": ["8080:80"],
    "api": ["8000-8002:8000", "8000-8002:8000", "8000-8002:8000", "8000-8002:8000"],
    "debug": ["5678", "5678"],
}, taken={8001, 32768})
web      8080:80        0.0.0.0:8080 -> 80/tcp
admin    8080:80        error: port 8080 is already allocated
api      8000-8002:8000 0.0.0.0:8000 -> 8000/tcp
api      8000-8002:8000 0.0.0.0:8002 -> 8000/tcp
api      8000-8002:8000 error: no free port in 8000-8002
api      8000-8002:8000 error: no free port in 8000-8002
debug    5678           0.0.0.0:32769 -> 5678/tcp
debug    5678           0.0.0.0:32770 -> 5678/tcp

admin loses the race for 8080. The range hands out 8000 and 8002 (8001 was already used by another program) and then runs dry. Unpublished-host ports get the next free port from the ephemeral range.

Scaling and ports

A fixed host port can belong to only one container, so docker compose up --scale api=3 fails if api publishes "8000:8000". Options: publish a range ("8000-8002:8000"), publish nothing and put a reverse proxy in front, or don't publish at all if only other services need the port. See Scaling & Resources.

Security: think about the host IP

"5432:5432" binds on 0.0.0.0, every interface of the host, including a public one. On Linux, Docker writes its own firewall rules for published ports, and they are evaluated before rules that tools like UFW add, so "the firewall blocks port 5432" may not be true. Habits that avoid accidents:

  • Publish only what must be reachable from outside, usually just the reverse proxy on 80/443.
  • For ports that only you need (databases, admin UIs, debuggers), bind to loopback: "127.0.0.1:5432:5432".
  • Use interpolation to make ports configurable, for example "${WEB_PORT:-8080}:80", so two developers with a busy 8080 don't edit the file.

Learn more: Networks · Service Discovery & DNS · Routing mesh in Swarm · Kubernetes Services

Test yourself

What does the short syntax "3000" publish?

  1. Host port 3000 to container port 3000
  2. Container port 3000 on a random free host port
  3. Nothing; it is the same as expose
  4. Port 3000 on 127.0.0.1

The api service needs to reach Postgres in the same project. What must the db service have?

  1. ports: ["5432:5432"]
  2. expose: ["5432"]
  3. Nothing: services on the same network can connect to any port the program listens on
  4. network_mode: host

Two services both publish "8080:80". When does Compose report the problem?

  1. docker compose config fails
  2. When up starts the second container: port is already allocated
  3. Never: Compose picks another port
  4. At build time