# Networking: bridge networks, published ports and container DNS

How containers talk: by name on a user-defined network, to the outside through published ports, and not at all across networks, with Docker's embedded DNS explained.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 10. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/docker/10-networking

## What you will learn

- Explain the default bridge, user-defined bridges, host and none networks
- Connect containers by name through Docker's embedded DNS at 127.0.0.11
- Prove that separate networks are isolated, and connect a container to two networks
- Publish ports safely, and know that published ports can bypass a host firewall
- Give several containers one network alias for simple load spreading

## Bridge networks

Before container networks, a team often hard-coded container IPs into application settings. Restarting one
container could change its address and break every caller. Docker networks connect isolated network namespaces
and, on user-defined bridges, let services find one another by name. In this lesson, you'll compare network
drivers, inspect bridge behavior, and decide which ports should be exposed outside the host.

Every container gets its own network namespace (lesson 2): its own interfaces, IP address and ports. A
**network** connects those namespaces. Docker starts with three:

```sh
$ docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
d781217f08f8   bridge    bridge    local
e3398db40859   host      host      local
6094544119b7   none      null      local
$ docker network inspect bridge --format '{{range .IPAM.Config}}{{.Subnet}} gw {{.Gateway}}{{end}}'
172.17.0.0/16 gw 172.17.0.1
```

| Network                                             | What the container gets                                     |
| --------------------------------------------------- | ----------------------------------------------------------- |
| `bridge` (default)                                  | an address on 172.17.0.0/16 behind NAT; **no** DNS by name  |
| a **user-defined bridge** (`docker network create`) | its own subnet, DNS by name, isolation from other networks  |
| `host`                                              | no namespace: the host's interfaces and ports, no isolation |
| `none`                                              | only a loopback interface                                   |

The default bridge is kept for old setups. Its biggest gap:

Use a user-defined bridge for containers that belong to the same application. Docker provides name-based DNS on
that network, so a client can call `api` instead of remembering a changing IP. Network membership also forms a
boundary: a container not attached to that bridge cannot use its service names through that network. Attach only
the services that need to communicate, and keep database ports unpublished unless a host-side client must reach
them. This gives you service discovery inside the host without making every container reachable from outside.

```sh
$ docker run -d --name a1 alpine:3.22 sleep 300
$ docker run -d --name a2 alpine:3.22 sleep 300
$ docker exec a1 ping -c1 a2
ping: bad address 'a2'
```

## Container DNS

Create your own network and names work:

```sh
$ docker network create appnet
$ docker run -d --name api --network appnet price-api:multi
$ docker run -d --name client --network appnet alpine:3.22 sleep 300
$ docker exec client wget -qO- api:8080/health
{"status":"ok","version":""}
$ docker exec client cat /etc/resolv.conf
nameserver 127.0.0.11
options ndots:0
$ docker exec client nslookup api 127.0.0.11 | grep -A1 Name
Name:	api
Address: 172.18.0.2
```

`127.0.0.11` is Docker's **embedded DNS server**. It answers with the containers on the same network and
forwards everything else (`example.com`) to the host's DNS. Use names, never container IPs: an IP changes
when the container is recreated, the name doesn't.

> **Figure.** Animated. Two networks. On appnet, a user-defined bridge, client asks the embedded DNS at 127.0.0.11 for api, gets 172.18.0.2 back, and gets status ok from api on port 8080. Container a1 is on the default bridge network: asking for api fails with bad address, and even the IP address times out, because the networks are isolated. After docker network connect appnet a1, a1 gets a second interface, 172.18.0.4, in appnet, and the same request succeeds.
>
> Names resolve inside a network. Between networks there's neither DNS nor a route until you connect them.

Networks are also a **security boundary**. From `a1`, on the default bridge, `api` doesn't exist, and even its
IP address isn't reachable:

```sh
$ docker exec a1 wget -qO- -T 3 api:8080/health
wget: bad address 'api:8080'
$ docker exec a1 wget -qO- -T 3 172.18.0.2:8080/health
wget: download timed out
$ docker network connect appnet a1                 # a second interface, in appnet
$ docker exec a1 wget -qO- api:8080/health
{"status":"ok","version":""}
```

A container can sit on several networks. That's how you split a stack: a `frontend` network with the proxy and
the API, a `backend` network with the API and the database. The proxy can't touch the database at all. In
Compose, list `networks:` per service.

### One name, several containers

```sh
$ docker run -d --name api2 --network appnet --network-alias backend price-api:multi
$ docker run -d --name api3 --network appnet --network-alias backend price-api:multi
$ docker exec client nslookup backend | grep Address | tail -2
Address: 172.18.0.6
Address: 172.18.0.5
```

DNS returns both addresses, so clients spread across them. It's crude (no health checks, clients cache
answers), but it's what Compose uses when you scale a service: `docker compose up -d --scale api=3`.

## Published ports

Containers on one network reach each other's ports directly. **Publishing** with `-p` is only for traffic from
outside, through the host:

```sh
$ docker run -d --name web -P nginx:1.30-alpine           # -P: every EXPOSEd port, random host ports
$ docker port web
80/tcp -> 0.0.0.0:32768
80/tcp -> [::]:32768
$ docker run -d --name web -p 127.0.0.1:8080:80 nginx:1.30-alpine
$ docker port web
80/tcp -> 127.0.0.1:8080
```

| Form                   | Listens on                                                    |
| ---------------------- | ------------------------------------------------------------- |
| `-p 8080:80`           | every host address, IPv4 and IPv6: reachable from the network |
| `-p 127.0.0.1:8080:80` | this machine only                                             |
| `-p 8080:80/udp`       | UDP instead of TCP                                            |
| `-P`                   | random high ports for every `EXPOSE` in the image             |

In lesson 9, only `web` published a port. `api` and `db` were reachable from inside `shop_default` and from
nowhere else. Publish the entry point; keep everything behind it unpublished.

Port publishing creates a path from a host address and port to a container port. For example, the host receives
traffic on 8080 and forwards it to port 80 in the container. Bind to loopback for local development so other
machines cannot connect through the host's network interface. Use an unrestricted host binding only when remote
clients are meant to reach the service, and then apply a firewall or load balancer policy. `EXPOSE` in an image
documents a port; it does not publish that port by itself.

> **Published ports can bypass your firewall.** Docker writes its own iptables rules for published ports, and on Linux they're processed before ufw's. `ufw deny 5432` won't stop `-p 5432:5432` from being reachable from the internet. Bind to `127.0.0.1`, filter in the `DOCKER-USER` chain, or use the cloud provider's firewall, and test from another machine.

> **In production.** Put a reverse proxy (nginx, Caddy, Traefik) or a load balancer in front, publish only 80 and 443, and keep databases on an internal network with no published port. Separate stacks get separate networks.

## Network drivers choose the isolation boundary

`bridge` is the normal isolated network; `host` shares the host namespace; `none` disables networking. `macvlan`
puts containers on a Layer-2 segment, while `overlay` connects Swarm nodes. IPv6 must be enabled deliberately.

> **Figure.** Docker network drivers compared: bridge for containers on one host, host sharing the host network stack, none with no networking, macvlan giving a container its own address on the LAN, and overlay spanning several hosts in a swarm.
>
> Pick the driver by where containers must talk: one host (bridge), the host itself (host), the LAN (macvlan) or many hosts (overlay).

> **Video.** [Docker Networking Tutorial (Bridge - None - Host - IPvlan - Macvlan - Overlay)](https://www.youtube.com/watch?v=fBRgw5dyBd4&t=132s) (Anton Putra)

```sh
$ docker run --rm --network none alpine:3.22 ip link
$ docker network ls --format '{{.Name}} {{.Driver}}'
$ docker inspect --format '{{json .NetworkSettings.Networks}}' api
```

## Mission: Split a stack into two networks

Create a frontend and a backend network. Put a proxy-like client on frontend, the API on both, and a database container on backend only. Prove the client can reach the API by name but can't resolve or reach the database.

- You need: Docker and the price-api image from lesson 7
- You'll have: wget api:8080/health succeeding from the client, and bad address for db

```sh
$ docker network create frontend && docker network create backend
$ docker run -d --name db --network backend -e POSTGRES_PASSWORD=devpass postgres:17-alpine
$ docker run -d --name api --network backend price-api:multi
$ docker network connect frontend api
$ docker run -d --name proxy --network frontend alpine:3.22 sleep 300
$ docker exec proxy wget -qO- api:8080/health
{"status":"ok","version":""}
$ docker exec proxy nslookup db 127.0.0.11 | grep -m1 NXDOMAIN
** server can't find db: NXDOMAIN
$ docker inspect api --format '{{range $k, $v := .NetworkSettings.Networks}}{{$k}} {{end}}'
backend frontend
$ docker rm -f db api proxy && docker network rm frontend backend
```

The API is the only container on both networks, so it's the only path to the database. If the proxy is ever
compromised, the database isn't even a name it can look up.

## Try it

- Start two containers on the default bridge and try to ping one by name.
- Create a network, start two containers on it, and reach one by name with wget.
- Read /etc/resolv.conf inside a container on a user-defined network.
- Run `nslookup api 127.0.0.11` from another container on the same network.
- Start nginx with `-P` and find the random host port with docker port.
- Run two containers with `--network-alias backend` and resolve backend.

## Quiz

1. Two containers on the default bridge network can't reach each other by name. Why?
   - Containers can never use names
   - **The default bridge has no name-based DNS; user-defined networks do** (answer)
   - A firewall blocks it
   - They need -p
   Why: docker network create appnet and --network appnet give you DNS by container name and service name. That is what Compose does for every project.

2. What answers DNS queries inside a container on a user-defined network?
   - The host's /etc/hosts
   - **Docker's embedded DNS server at 127.0.0.11, which knows the containers on that network and forwards other names** (answer)
   - Google DNS
   - The container itself
   Why: /etc/resolv.conf inside points to 127.0.0.11. Names of containers on other networks are not answered.

3. Why does -p 8080:80 on a cloud server deserve a second look?
   - It is slow
   - **It listens on every interface, and Docker adds its own firewall rules, which can bypass ufw** (answer)
   - It needs root inside the container
   - Ports below 1024 fail
   Why: Bind to 127.0.0.1 when only a local reverse proxy needs it, and filter in the DOCKER-USER chain or a cloud firewall.

4. Does a container need -p to talk to another container on the same network?
   - Yes, always
   - **No; -p only maps a port to the host. Containers on one network reach each other's ports directly** (answer)
   - Only for TCP
   - Only in Compose
   Why: In lesson 9, only web published a port. api and db were reachable from inside the network and nowhere else, which is what you want.

5. What does --network host do?
   - Creates a new network named host
   - **Skips the network namespace: the container uses the host's interfaces and ports directly** (answer)
   - Publishes every port
   - Blocks all traffic
   Why: No isolation and no -p. Useful for some network tools; avoid it for normal services. --network none gives only a loopback.

## Resources

- [Docker Docs: networking overview](https://docs.docker.com/engine/network/) (Docker Docs)
- [Docker Docs: bridge network driver](https://docs.docker.com/engine/network/drivers/bridge/) (Docker Docs)
- [Docker Docs: port publishing and mapping](https://docs.docker.com/engine/network/port-publishing/) (Docker Docs)
- [Docker Docs: packet filtering and firewalls](https://docs.docker.com/engine/network/packet-filtering-firewalls/) (Docker Docs)
