How to Safely Manage iptables with Docker Compose

How to protect iptables when using docker-compose. By default, Docker dynamically modifies iptables rules, which prevents normal firewall management. Many guides suggest saving Docker rules and restoring them later — I don't think this is a good approach. If Docker cannot handle firewall tasks properly, let's free it from this responsibility. See also docker-compose demonization with systemd.

This example shows how to disable Docker’s automatic iptables management, set up static NAT rules, and configure docker-compose networks safely.

No automatic iptables management

# cat /etc/docker/daemon.json 
{  "log-driver": "journald",  "iptables": false}

Static NAT configuration

#!/bin/sh

/sbin/iptables -t nat -F PREROUTING
/sbin/iptables -t nat -F POSTROUTING
/sbin/iptables -A POSTROUTING -s 10.100.0.1/24 -o docker0 -j MASQUERADE -t nat
/sbin/iptables -A POSTROUTING -s 10.100.0.1/24 -o eth0 -j MASQUERADE -t nat

/sbin/iptables -A FORWARD -i docker0 -o docker0 -j ACCEPT
/sbin/iptables -A FORWARD -i docker0 -o eth0 -j ACCEPT
/sbin/iptables -A FORWARD -i eth0 -o docker0 -j ACCEPT

docker-compose.yml configuration (version 3)

version: '3'
...
networks:
  default:
    driver: bridge
    driver_opts: {com.docker.network.enable_ipv6: 'false'}
    ipam:
      config:
      - {subnet: 10.100.0.1/24}
      driver: default
...
services:
  nginx-d1:
    container_name: nginx-d1
    hostname: nginx-d1
    image: nginx:1.14
    links: [fluentd, php-d1]
    logging:
      driver: fluentd
      options: {tag: nginx-d1}
    ports: ['443:443', '80:80']
    volumes: [
      '/data/code:/code', 
      '/srv/docker-compose/configs/nginx-d1/conf.d:/etc/nginx/conf.d'
    ]
...
Human Logic, AI Syntax... Note on Content: I'm a Systems Engineer, not a native English writer. To ensure my technical ideas are clear and accessible, I use AI tools to polish the grammar and style. The workflow is simple: I provide the logic, the code, and the real-world experience. The AI handles the "English-to-Human" translation layer. If you find a bug, that's on me. If you find a perfectly placed comma, that's probably the AI.

Comments

Popular posts from this blog

FreeRadius with Google Workspace LDAP

Fixing pssh (parallel-ssh) Problems on Debian 10 with Python 3.7