Eu enfrentei um problema que não posso encaminhar na interface lo de um contêiner de qualquer porta para outro contêiner que estava vinculado a este. Depois de horas, nasceram as funções abaixo =)
Exemplo simples:
forward_port webserver 80 mysql 80
As funções do bash:
SUDO=""
if [ "$(id -u)" != "0" ]; then
SUDO='which sudo 2> /dev/null'
fi
########################################
# Forward port xxx from a container CT_SRC to a container CT_DST dest port yyyy
########################################
# EXAMPLE:
# forward_port b7cbbdc83aed 80 6a513762267f 80
#######################################
function forward_port()
{
#set +x
# CT_ID of container where you need
local CT_SRC=${1:-}
# local CT_SRC_INTERFACE=${2:-}
local CT_SRC_PORT=${2:-}
local CT_DST=${3:-}
local CT_DST_PORT=${4:-}
local CT_SRC_IP=$(${SUDO} docker inspect --format='{{ .NetworkSettings.IPAddress}}' "$CT_SRC")
# if [[ "$CT_SRC_INTERFACE" =~ ^lo.* ]];then
# CT_SRC_IP="127.0.0.1"
# fi
local CT_DST_IP=$(${SUDO} docker inspect --format='{{ .NetworkSettings.IPAddress}}' "$CT_DST")
local DOCKERPID=$(${SUDO} docker inspect --format='{{ .State.Pid }}' "$CT_SRC")
local NSPID=$DOCKERPID
[ ! -d /var/run/netns ] && mkdir -p /var/run/netns
rm -f "/var/run/netns/$NSPID"
ln -s "/proc/$NSPID/ns/net" "/var/run/netns/$NSPID"
local LOCAL_IP=${CT_SRC_IP}
local LPORT=${CT_SRC_PORT}
local REMOTE_HOST=${CT_DST_IP}
local RPORT=${CT_DST_PORT}
local ip_ns="ip netns exec $NSPID"
${SUDO} $ip_ns sysctl -w net.ipv4.conf.all.route_localnet=1 > /dev/null
${SUDO} $ip_ns iptables -t nat -A OUTPUT -m tcp -p tcp --dport $LPORT -j DNAT --to $REMOTE_HOST:$RPORT > /dev/null
${SUDO} $ip_ns iptables -t nat -A POSTROUTING -m tcp -p tcp --dport $LPORT --dst $REMOTE_HOST -j SNAT --to-source $LOCAL_IP > /dev/null
}
#################################################################
#
# Flush forwarding rules & create namespace for CT_ID
#
#################################################################
function flush_forward_rules()
{
local CT_ID=${1:-}
local DOCKERPID=$(docker inspect --format='{{ .State.Pid }}' "$CT_ID")
local NSPID=$DOCKERPID
[ ! -d /var/run/netns ] && mkdir -p /var/run/netns
rm -f "/var/run/netns/$NSPID"
ln -s "/proc/$NSPID/ns/net" "/var/run/netns/$NSPID"
local ip_ns="ip netns exec $NSPID"
$ip_ns iptables -F
$ip_ns iptables -t nat -F
$ip_ns iptables -X
$ip_ns iptables -F
$ip_ns iptables -X
$ip_ns iptables -t nat -F
$ip_ns iptables -t nat -X
$ip_ns iptables -t mangle -F
$ip_ns iptables -t mangle -X
$ip_ns iptables -P INPUT ACCEPT
$ip_ns iptables -P FORWARD ACCEPT
$ip_ns iptables -P OUTPUT ACCEPT
}