User Tools

Site Tools


docker:firewall-allow-internet-from-containers

Docker Firewall Configuration (firewalld)

Why are these commands needed?

The following commands are essential to allow Docker containers to communicate properly with the external network when using firewalld as the system firewall:

sudo firewall-cmd --add-masquerade --permanent
sudo firewall-cmd --reload
sudo systemctl restart docker

Detailed Explanation

1. Masquerade (NAT)

Command:

sudo firewall-cmd --add-masquerade --permanent

Why it's needed: * Docker uses internal virtual networks for containers * Containers have private IP addresses (typically in the 172.17.0.0/16 range) * Masquerade (NAT - Network Address Translation) enables:

  1. Containers to access the internet
  2. Outbound traffic to use the host's IP address
  3. Inbound connections to be routed to the correct containers

Analogy: Like a post office that receives mail for apartments in a building and delivers it to the correct recipients.

2. Reload firewall

Command:

sudo firewall-cmd --reload

Why it's needed: * Applies configuration changes made with the –permanent option * Firewall rules become immediately active * Ensures settings persist after reboot

3. Restart Docker

Command:

sudo systemctl restart docker

Why it's needed: * Docker needs to detect the new firewall rules * Reloads network configuration * Ensures new containers will benefit from updated settings

What happens without these settings?

* Containers cannot access the internet * Services in containers are not accessible from outside * Network connections fail * Port forwarding doesn't work correctly

Practical Example

After running these commands, you can run:

docker run -p 80:80 nginx

And the nginx server will be accessible from your network at: http://host-ip-address

Verification

To verify that masquerade is enabled:

firewall-cmd --query-masquerade

Should return yes.

Important Notes

* These settings are only needed if you use firewalld * On systems with direct iptables, Docker manages rules automatically * Settings are persistent due to the –permanent option

Additional Resources

docker/firewall-allow-internet-from-containers.txt · Last modified: 2025/08/25 23:25 by odefta