Created
September 6, 2017 23:36
-
-
Save freman/70ef91129d4983f0300ab4b53fd9d89c to your computer and use it in GitHub Desktop.
Re-create docker iptables rules
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this script saved my day. thanks)