# Ports and Exposure — Docker Compose

Source: https://www.skillbyai.com/en/docker-compose/s-ports

> Publish only what the host needs.

## HOST:CONTAINER

`ports: ["8080:80"]` publishes container port 80 on host port 8080, reachable from your machine (and, by default, from other machines that can reach it). Services do **not** need published ports to talk to each other: on the project network they reach each other by service name and container port (`http://api:3000`). Publish only what humans or external clients must reach, and bind development-only ports to localhost (`"127.0.0.1:5432:5432"`) to avoid exposing databases on the network.

## Port patterns

Choose the narrowest exposure.

```yaml
ports:
  - "8080:80"              # host 8080 -> container 80, on all host interfaces
  - "127.0.0.1:5432:5432"  # only from this machine (good for dev databases)
# no ports at all: still reachable by other services as db:5432 on the project network
```

## Do not publish databases

Inside the Compose network the API reaches db:5432 without any published port; publish it only on localhost when you need a local client.

**Quiz:** Does the api service need a published port to reach db?

- [ ] Yes, always
- [x] No, services reach each other by name on the project network
- [ ] Only on Windows
- [ ] Only with host networking

*Answer:* No, services reach each other by name on the project network. Publishing is for access from outside.
