How to Use Ports in Docker Compose: Syntax and Examples
In
docker-compose.yml, use the ports key under a service to map container ports to host ports with the syntax HOST_PORT:CONTAINER_PORT. This allows external access to services running inside containers by forwarding traffic from the host to the container.Syntax
The ports section in a docker-compose.yml file maps ports from the host machine to the container. The format is HOST_PORT:CONTAINER_PORT, where:
- HOST_PORT: The port on your computer or server.
- CONTAINER_PORT: The port inside the container where the service listens.
This mapping allows you to access the containerized service through the host port.
yaml
services:
myservice:
image: myimage
ports:
- "HOST_PORT:CONTAINER_PORT"Example
This example shows a simple Docker Compose file that runs an Nginx web server. It maps port 8080 on the host to port 80 inside the container, so you can open http://localhost:8080 in your browser to see the web page served by Nginx.
yaml
version: '3.8' services: web: image: nginx:stable ports: - "8080:80"
Output
Starting web ... done
# After running 'docker-compose up', visiting http://localhost:8080 shows the Nginx welcome page.
Common Pitfalls
Common mistakes when using ports in Docker Compose include:
- Not quoting port mappings, which can cause YAML parsing errors.
- Using the same host port for multiple services, causing conflicts.
- Forgetting to expose the container port in the Dockerfile or service, so the service is not reachable.
- Assuming
portspublishes the port to the host automatically without specifying it.
Always check that the host port is free and that the container service listens on the mapped port.
yaml
services:
app1:
image: myapp1
ports:
- "8080:80" # Correct: quoted string recommended
app2:
image: myapp2
ports:
- "8080:80" # Conflict: same host port as app1
# Fix by using different host ports:
services:
app1:
image: myapp1
ports:
- "8080:80"
app2:
image: myapp2
ports:
- "8081:80"Quick Reference
| Term | Description |
|---|---|
| ports | Key to define port mappings in docker-compose.yml |
| HOST_PORT:CONTAINER_PORT | Format to map host port to container port |
| Quoted strings | Use quotes around port mappings to avoid YAML errors |
| Port conflicts | Avoid using the same host port for multiple services |
| Container port | Must match the port the service listens on inside the container |
Key Takeaways
Use the ports key with format HOST_PORT:CONTAINER_PORT to expose container ports.
Always quote port mappings in docker-compose.yml to prevent YAML parsing issues.
Avoid port conflicts by assigning unique host ports for each service.
Ensure the container service listens on the container port you map.
Test access by visiting localhost:HOST_PORT after starting the containers.