You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. 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:latest
    
  2. Fetch 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)
    
  3. Add iptables rules to block reverse traffic:
    Docker reserves the DOCKER-USER chain 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 ACCEPT
    
  4. Persist 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:39:37