BudiBadu Logo
Samplebadu

Docker Compose by Example: Port Exposure

Compose Specification v2

Mapping container ports to host with this code example showing HOST:CONTAINER syntax, binding to specific host interfaces, port range mapping, protocol specification for UDP, and security considerations.

Code

services:
  web:
    image: nginx:alpine
    ports:
      # "HOST:CONTAINER"
      - "8080:80"
      
      # Bind to specific host IP (localhost only)
      - "127.0.0.1:8081:80"
      
      # Range of ports
      - "3000-3005:3000-3005"
      
      # UDP protocol
      - "53:53/udp"
      
  db:
    image: postgres:15
    # Don't expose ports if only internal services need access
    # ports:
    #   - "5432:5432"

Explanation

Port mapping bridges host machines and container networks, with the ports directive specifying which host ports forward to container ports. The syntax "HOST_PORT:CONTAINER_PORT" requires quoting to avoid YAML parsing ambiguity where XX:YY could be interpreted as base-60 numbers. Port mappings enable accessing containerized services from outside Docker networks.

Security considerations require mindful interface binding. Mapping ports like "8080:80" defaults to binding 0.0.0.0, making services accessible from any network interface on the host. For development environments requiring local-only access, specify the loopback address: "127.0.0.1:8080:80". This prevents external network access while allowing local development and testing.

Services used exclusively by other containers, like databases accessed only by backend APIs, typically don't require port mappings. Containers on the same Docker network communicate using internal ports directly through DNS resolution. Port mapping is only necessary when accessing services from outside Docker, such as web browsers connecting to web servers or database clients connecting to databases.

Code Breakdown

6
"8080:80" maps host port 8080 to container port 80, access at http://localhost:8080.
9
"127.0.0.1:..." restricts access to local machine, prevents external network access.
12
"3000-3005:3000-3005" maps port range for multiple concurrent connections.
15
"53:53/udp" specifies UDP protocol for DNS, defaults to TCP without suffix.