Docker自定义网络:默认禁容器通信的方案弊端及单向访问疑问
问题2:实现webServerContainer到dbContainer的单向通信
Docker’s default network model is bidirectional, so we’ll use iptables rules to enforce one-way traffic. Here’s a practical, host-level approach that works for standalone Docker:
Group containers in a custom network (this ensures they can resolve each other by name and stay isolated from other containers):
docker network create app-private-network docker run -d --name webServerContainer --network app-private-network your-web-image:latest docker run -d --name dbContainer --network app-private-network your-db-image:latestFetch container IPs (we’ll use these for precise iptables targeting):
# Get web server's internal IP WEB_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' webServerContainer) # Get database's internal IP DB_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' dbContainer)Add iptables rules to block reverse traffic:
Docker reserves theDOCKER-USERchain for user-defined firewall rules—this is the safest place to add your rules (they won’t be overwritten by Docker’s internal networking):# Block all outgoing traffic from dbContainer to webServerContainer iptables -A DOCKER-USER -s $DB_IP -d $WEB_IP -j DROP # Optional: Explicitly allow traffic from webServerContainer to dbContainer (this is default, but adds clarity) iptables -A DOCKER-USER -s $WEB_IP -d $DB_IP -j ACCEPTPersist rules (optional but recommended):
To keep these rules after a host reboot, save them to your system’s iptables config:# For Debian/Ubuntu iptables-save > /etc/iptables/rules.v4 # For RHEL/CentOS iptables-save > /etc/sysconfig/iptables
Alternative: Container-level isolation
If you want to apply the rule directly to dbContainer instead of the host, use nsenter to modify its network namespace:
# Get the container's PID DB_PID=$(docker inspect -f '{{.State.Pid}}' dbContainer) # Block outgoing traffic to the web server from within the container nsenter -t $DB_PID -n iptables -A OUTPUT -d $WEB_IP -j DROP
Note: This rule will reset if the container restarts, so add it to your container’s startup script or entrypoint wrapper to reapply it on boot.
内容的提问来源于stack exchange,提问作者Ray J

