Skip to content

Instantly share code, notes, and snippets.

@gomin1d
Forked from freman/evalmyoutput.sh
Last active January 23, 2022 02:17
Show Gist options
  • Save gomin1d/8fa5cdf2b27c46f9fdcb79b9578ba795 to your computer and use it in GitHub Desktop.
Save gomin1d/8fa5cdf2b27c46f9fdcb79b9578ba795 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
address=$(docker inspect "${container}" -f '{{.NetworkSettings.Networks.'"$network"'.IPAddress}}');
if [ "$address" == "<no value>" ]; 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}}{{if ne $map.HostIp "::"}}{{"\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}}{{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