Skip to content

Instantly share code, notes, and snippets.

@chaddupuis
Created November 14, 2023 21:11
Show Gist options
  • Save chaddupuis/749201290be58db302c8df767ff7fe26 to your computer and use it in GitHub Desktop.
Save chaddupuis/749201290be58db302c8df767ff7fe26 to your computer and use it in GitHub Desktop.
Docker - Allow Communication Between Two Bridged Networks On Same Host (via iptables)
#!/bin/bash
## If docker containers are running on two separate bridge networks,
## by default they cannot communicate
## To selectively allow this you can use iptables rules to allow communication.
## This script, connects an app ("webapp") to a database ("postgres") running on separate networks.
postgresip=$(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' postgres)
webappip=$(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' webapp)
postgresipgw=$(echo $postgresip | sed 's/\.[0-9]*$/.1/')
webappipgw=$(echo $webappip | sed 's/\.[0-9]*$/.1/')
postgresbr=$(ip -4 -brief address show | grep ${postgresipgw} | awk '{print $1}')
webappbr=$(ip -4 -brief address show | grep ${webappipgw} | awk '{print $1}')
echo $postgresip
echo $webappip
echo $postgresipgw
echo $webappipgw
echo $postgresbr
echo $webappbr
# find the current rules to drop
rulesarray=($(iptables --list DOCKER-USER --line-numbers| grep ACCEPT | awk '{print $1}'))
## Depending on other apps on the system it might be more reliable to
## do a flush and save instead of the selective deletes below
## iptables -F DOCKER-USER
## service iptables save
for i in "${rulesarray[@]}"
do
echo "removing docker-user chain rule ${i}"
iptables -D DOCKER-USER ${i}
done
echo "saving the cleaned ruleset"
service iptables save
# set the new rules and save
echo "creating the bridged communication rules for webapp<-->postgres"
iptables -A DOCKER-USER -i ${postgresbr} -o ${webappbr} -s ${postgresip} -d ${webappip} -j ACCEPT
iptables -A DOCKER-USER -i ${webappbr} -o ${postgresbr} -s ${webappip} -d ${postgresip} -j ACCEPT
echo "saving rules"
service iptables save
echo "finished opening firewall between postgres<-->webapp"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment