How to Fix Docker 502 Bad Gateway on Debian 11
The Root Cause
On Debian 11, the default firewall backend is nftables. Docker, by default, often relies on iptables-legacy for managing network rules and port forwarding. This discrepancy can lead to conflicts where nftables interferes with Docker’s ability to expose container ports, causing proxy services to fail with a “502 Bad Gateway” when attempting to connect.
Quick Fix (CLI)
The most common immediate resolution is to explicitly configure Debian 11 to use iptables-legacy for all iptables operations, ensuring Docker’s networking rules are applied correctly.
sudo update-alternatives --set iptables /usr/sbin/iptables-legacy
sudo update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy
sudo systemctl restart docker
Configuration Check
If the quick fix does not fully resolve the issue, or to further solidify Docker’s network behavior, consider disabling Docker’s userland proxy. This forces Docker to rely purely on iptables rules for port forwarding, which can sometimes circumvent subtle networking problems when interacting with host firewalls.
Edit or create /etc/docker/daemon.json:
{
"userland-proxy": false
}
After modifying daemon.json, restart the Docker daemon:
sudo systemctl restart docker
Verification
Confirm the Docker daemon is running, your container is active and healthy, and then attempt to access your service.
sudo systemctl status docker
docker ps -a
curl -I http://localhost:<YOUR_MAPPED_PORT>
# Or, if using a domain with a proxy:
curl -I https://your-domain.com