#! /bin/sh # From https://fruit.je/docker-and-iptables. # By Wessel Dankers , 2024 # License: WTFPL version 2, see file WTFPL-2 or # http://www.wtfpl.net/txt/copying/ set -e if command -v jq >/dev/null 2>&1 then : else echo >&2 docker-netns: jq: command not found. please apt install jq. exit 1 fi for fwd in /proc/sys/net/ipv4/ip_forward /proc/sys/net/ipv6/conf/*/forwarding do echo 1 >$fwd done ip link del docker 2>/dev/null || exec ip netns del docker 2>/dev/null || exec ip netns add docker ip link add dev docker type veth peer name eth0 netns docker ip link set docker up ip -n docker link set lo up ip -n docker link set eth0 up ip4=$(exec 2>/dev/null; ip -j route get 1.1.1.1 | jq -r '.[0].prefsrc' || exec) case $ip4 in ?*) ip addr add dev docker 172.16.0.1/24 ip -n docker addr add dev eth0 172.16.0.2/24 ip -n docker route add default via 172.16.0.1 dev eth0 # Put this in your own firewall rulebase: echo iptables -t nat -A POSTROUTING -s 172.16.0.0/24 -j SNAT --to-source $ip4 esac ip6=$(exec 2>/dev/null; ip -j route get 2600:: | jq -r '.[0].prefsrc' || exec) case $ip6 in ?*) ula=$(hostname --fqdn|sha256sum|sed -r 's/^(..)(....)(....).*/fd\1:\2:\3/') ip addr add dev docker $ula::1/64 ip addr add dev docker $ula::/128 preferred_lft 0 ip -n docker addr add dev eth0 $ula::2/64 ip -n docker route add default via $ula:: dev eth0 # Put this in your own firewall rulebase: echo ip6tables -t nat -A POSTROUTING -s $ula::/64 -j SNAT --to-source $ip6 esac