Port Mapping and Exposure
What you'll learn: How to configure port mappings in Docker Compose to control which container services are accessible from the host and external networks.
The Core Concept
When containers run, they have their own internal network. Port mapping creates a bridge between ports inside your container and ports on your host machine, making services accessible. Without proper mapping, your containerized web app or database remains invisible to the outside world.
Think of it like an apartment building: each apartment (container) has its own door number (internal port), but you need a building entrance number (host port) that visitors can use to reach the right apartment.
Using ports in Docker Compose
The ports directive publishes container ports to the host:
services:
web:
image: nginx
ports:
- "8080:80" # host:container
- "443:443"
Here, traffic to localhost:8080 on your machine routes to port 80 inside the container. The format is always HOST:CONTAINER.
Using expose for Internal Communication
The expose directive documents which ports are available but only within the Docker network—not to the host:
services:
api:
image: my-api
expose:
- "3000"
web:
image: nginx
ports:
- "80:80"
The api service's port 3000 is accessible to web via the Docker network, but not directly from your machine. This improves security by limiting external access.
When to Use Each
ports: Use when you need external access (browsers, external services)expose: Use for service-to-service communication within your Compose stack
Key Takeaway: Port mapping with ports makes containers accessible externally, while expose documents internal connectivity—together they control the boundaries of your containerized services.