Sub topic 13
Limiting container networking and published ports
This chapter assumes you can write a Dockerfile and run containers, and that you know what an IP address, a TCP port, and a firewall rule are. It also assumes you've read the earlier chapters on capabilities and runtime limits. Here you'll learn how a container becomes reachable, which defaults are too permissive, and how to shrink the network surface to what the application needs.
How containers are reachable by default
A container on the default bridge network gets a private IP address and can make outbound connections to anywhere the host can reach. Nothing outside the host can connect in until you publish a port.
Publishing a port with -p (or ports: in Compose) tells Docker to add NAT rules in the host firewall. By default, -p 8080:80 binds to 0.0.0.0, meaning every network interface on the host. If the host has a public address, the service is on the internet.
Three points cause most mistakes:
EXPOSEin a Dockerfile only documents a port. It does not publish anything.-P(capital) publishes every exposed port to a random high host port on all interfaces. Avoid it outside experiments.- Docker writes its own iptables rules. Rules added by tools such as
ufworfirewalldoften do not filter published container ports, because Docker's NAT and forwarding rules are evaluated before them. A port can be open even thoughufw statusshows it denied.
Publish only what you need, only where you need it
Choose the narrowest binding that works.
| Goal | Publish flag | Reachable from |
|---|---|---|
| Service used only by a reverse proxy on the same host | `-p 127.0.0.1:8080:8080` | The host itself |
| Service for one internal interface | `-p 10.0.0.5:8080:8080` | Clients that can reach that address |
| Public service | `-p 8080:8080` | Every interface |
| Service used only by other containers | No `-p` | Containers on a shared network |
Containers that talk to each other do not need published ports. They reach each other over a shared Docker network by container or service name.
docker run -d --name web \
-p 127.0.0.1:8080:8080 \
myapp:1.0
docker port web
ss -ltnp | grep 8080docker port web shows the mapping and ss shows the listening address on the host. Check that the address is 127.0.0.1:8080 and not 0.0.0.0:8080 or [::]:8080. IPv6 bindings are a common miss: if you publish on 0.0.0.0 only, check whether Docker also created an IPv6 listener on your version and configuration.
You can change the default binding address for all published ports in /etc/docker/daemon.json:
{
"ip": "127.0.0.1"
}With this setting, -p 8080:8080 binds to loopback unless the command names another address. Restart the daemon after editing. This makes a forgotten bind address safe instead of public.
Use user-defined networks, not the default bridge
The default bridge network has weaker properties than a user-defined bridge:
- All containers on it can reach each other by IP address, whether or not they need to.
- It has no automatic DNS-based name resolution between containers, so people fall back to legacy links or fixed IPs.
- Any unrelated container started without a
--networkflag lands on it.
Create a user-defined network for each application, and attach containers to it explicitly. Containers on different user-defined networks cannot reach each other unless you connect them to a common network.
docker network create frontend
docker network create --internal backend
docker run -d --name cache --network backend redis:7
docker run -d --name web --network frontend -p 127.0.0.1:8080:8080 myapp:1.0
docker network connect backend webHere web sits on both networks and can reach cache. A container on frontend only cannot. The --internal flag on backend blocks traffic to and from outside the network, so cache cannot make outbound connections and cannot be reached through the host.
Express the same layout in Compose
Compose creates a project network by default and puts every service on it. Define networks yourself when services have different exposure needs.
services:
web:
image: myapp:1.0
ports:
- "127.0.0.1:8080:8080"
networks:
- frontend
- backend
cache:
image: redis:7
networks:
- backend
networks:
frontend: {}
backend:
internal: trueReview the ports: section of every Compose file as part of code review. A line such as "5432:5432" on a database service is a frequent cause of exposed databases.
Disable networking when it is not needed
A batch job that reads a file and writes a result needs no network. Remove it:
docker run --rm --network none \
--read-only --cap-drop ALL \
myapp:1.0 process-fileWith --network none, the container has only a loopback interface. An attacker who gets code execution cannot easily exfiltrate data or fetch tools.
Avoid host networking
--network host removes network namespace isolation. The container shares the host's interfaces and sees its listening sockets. A process in the container can bind any host port, reach services bound to host loopback (including, in some setups, local admin endpoints), and port filtering by Docker no longer applies. Treat --network host the way you treat --privileged: use it only when you can state why nothing else works, and then pair it with dropped capabilities and a non-root user.
Restrict traffic between containers and to the outside
Inter-container communication on the default bridge
Setting "icc": false in daemon.json stops containers on the default bridge from talking to each other unless linked. It does not affect user-defined networks, where you control reachability by choosing which networks a container joins. This is why separate networks are the main tool, and icc is a secondary measure for legacy setups.
{
"icc": false
}Filtering with the DOCKER-USER chain
Docker evaluates the DOCKER-USER iptables chain before its own rules and never overwrites it, so it is the supported place for your own filters. Remember that rules there see traffic after destination NAT. A --dport match refers to the container's port, not the host's published port.
This example drops traffic to container port 8080 unless it comes from the 203.0.113.0/24 network, on host interface eth0:
sudo iptables -I DOCKER-USER -i eth0 -p tcp --dport 8080 ! -s 203.0.113.0/24 -j DROPRules added this way are lost on reboot unless you persist them with your distribution's tooling. Test from outside the host with nc -vz <host-ip> 8080.
Egress control
Docker has no built-in outbound allow-list. A compromised container on a normal bridge network can reach the internet and any internal address the host can reach, such as cloud metadata endpoints. Options, from simplest to most involved:
- Put the container on an
--internalnetwork when it needs no outside access. - Add
DOCKER-USERrules that drop traffic from the container subnet to sensitive ranges, for example169.254.169.254on cloud hosts. - Route traffic through a proxy container on a network that has outbound access, and give the application containers only the internal network.
Encrypt traffic that leaves the host
Traffic on a bridge network stays on the host and is not encrypted. On multi-host setups, Swarm overlay networks are unencrypted by default. Create them with --opt encrypted to turn on IPsec encryption of the VXLAN data plane:
docker network create --driver overlay --opt encrypted app-netEncryption adds CPU cost and needs the ESP protocol (IP protocol 50) permitted between nodes. For traffic carrying credentials or personal data, many teams add TLS at the application layer regardless.
Verify what you built
Check the result instead of trusting the configuration:
docker ps --format 'table {{.Names}}\t{{.Ports}}'
docker network inspect backend --format '{{.Internal}}'
docker inspect web --format '{{json .NetworkSettings.Networks}}'The first command lists published ports for every running container, and any 0.0.0.0 or [::] entry deserves a justification. The second prints true for an internal network. The third shows which networks a container has joined. From another machine, run a port scan against the host with a tool such as nmap (on systems you are authorized to test) and compare the open ports to your expected list.
Common errors
- Database published to all interfaces.
-p 5432:5432for a service only the app needs. Remove the mapping and use a shared network. - Assuming the host firewall protects published ports. Verify from outside the host.
- Putting everything on one network. A compromise of the public-facing container then reaches every other service. Split by tier.
- Using
--internaland expecting published ports to work. Published ports are not available for containers attached only to an internal network. Attach the container to a second, non-internal network for that. - Mounting the Docker socket instead of fixing networking. Covered in the daemon chapter. It gives far more access than any network rule can take away.
Exercise
A Compose file has services api and db. db runs PostgreSQL with ports: ["5432:5432"], and only api needs to talk to it. The API should be reachable only from a reverse proxy running on the same host. What changes would you make to the networking?
Show answer
Remove the ports: entry from db so PostgreSQL is not published, and put db on a user-defined network with internal: true, shared with api. Change api ports to "127.0.0.1:8080:8080" (using the API's real port) so only the host's reverse proxy can reach it. Then verify with docker ps --format 'table {{.Names}}\t{{.Ports}}' that no 0.0.0.0 bindings remain, and with docker network inspect that the database network is internal.
Exercise
You run ufw deny 8080, but a container published with -p 8080:8080 is still reachable from another machine. Why, and what are two ways to fix it?
Show answer
Docker inserts its own NAT and forwarding rules in iptables that are evaluated before the rules ufw manages, so ufw does not filter published container ports. Fix it by publishing on a specific address (for example -p 127.0.0.1:8080:8080), or by adding a drop rule in the DOCKER-USER chain, remembering that the port matched there is the container's port after NAT.