Skip to content

Instantly share code, notes, and snippets.

@freman
Created September 6, 2017 23:36
Show Gist options
  • Save freman/70ef91129d4983f0300ab4b53fd9d89c to your computer and use it in GitHub Desktop.
Save freman/70ef91129d4983f0300ab4b53fd9d89c to your computer and use it in GitHub Desktop.
Re-create docker iptables rules
#!/bin/bash
echo "Recreating docker iptables rules and chains"
echo "iptables -N DOCKER"
echo "iptables -N DOCKER-ISOLATION"
echo "iptables -t nat -N DOCKER"
echo "iptables -A DOCKER-ISOLATION -j RETURN"
echo "iptables -A FORWARD -j DOCKER-ISOLATION"
echo "iptables -t nat -A PREROUTING -m addrtype -dst-type LOCAL -j DOCKER"
echo "iptables -t nat -A OUTPUT ! -d 127.0.0.0/8 -m addrtype -dst-type LOCAL -j DOCKER"
for network in $(docker network ls -f 'driver=bridge' --format '{{.Name}}'); do
iface=$(docker network inspect "${network}" -f '{{range $n, $iface := .Options}}{{if eq $n "com.docker.network.bridge.name"}}{{$iface}}{{end}}{{end}}')
echo "iptables -A INPUT -i ${iface} -j ACCEPT"
echo "iptables -A FORWARD -o ${iface} -j DOCKER"
echo "iptables -A FORWARD -o ${iface} -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT"
echo "iptables -A FORWARD -i ${iface} ! -o ${iface} -j ACCEPT"
echo "iptables -A FORWARD -i ${iface} -o ${iface} -j ACCEPT"
echo "iptables -t nat -A DOCKER -i ${iface} -j RETURN"
for container in $(docker network inspect bridge -f '{{range $name,$trash := .Containers}}{{$name}}{{"\x0a"}}{{end}}'); do
if [ -z "$container" ]; then
continue
fi
echo -ne "# $container"
docker inspect "${container}" -f '{{$addr:=.NetworkSettings.Networks.'"$network"'.IPAddress}}{{range $dport, $maps := .NetworkSettings.Ports}}{{$ddport := split $dport "/"}}{{range $index,$map := $maps}}{{"\x0a"}}iptables -A DOCKER -p {{index $ddport 1}} ! -i '"$iface"' -o '"$iface"' -d {{$addr}} --dport {{index $ddport 0}} -j ACCEPT {{"\x0a"}}iptables -t nat -A DOCKER ! -i '"$iface"' -p {{index $ddport 1}} --dport {{$map.HostPort}} -d {{$map.HostIp}} -j DNAT --to-destination {{$addr}}:{{index $ddport 0}}{{end}}{{end}}'
done
docker network inspect "${network}" -f '{{$f:=.}}{{range $n, $iface := .Options}}{{if eq $n "com.docker.network.bridge.name"}}{{range $i, $cfg := $f.IPAM.Config}}iptables -t nat -A POSTROUTING ! -o {{$iface}} -s {{$cfg.Subnet}} -j MASQUERADE{{"\x0A"}}{{end}}{{end}}{{end}}'
done
@igroykt
Copy link

igroykt commented Feb 22, 2022

this script saved my day. thanks)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment