Custom outgoing IP from docker container

Hi. If You want to configure a custom docker container to use one public IPs that are located on the host system You can use this schema.

First, need install docker engine on the system  - install docker 
Next, create docker networks like this

---------------------------------------------------------

docker network create --attachable --opt 'com.docker.network.bridge.name=my-network-1' --opt 'com.docker.network.bridge.enable_ip_masquerade=false' --subnet=172.20.10.0/24 --gateway=172.20.10.1 my-network-1

docker network create --attachable --opt 'com.docker.network.bridge.name=my-network-2' --opt 'com.docker.network.bridge.enable_ip_masquerade=false'  --subnet=172.20.20.0/24 --gateway=172.20.20.1 my-network-2

docker network create --attachable --opt 'com.docker.network.bridge.name=my-network-3' --opt 'com.docker.network.bridge.enable_ip_masquerade=false' --subnet=172.20.30.0/24 --gateway=172.20.30.1 my-network-3

---------------------------------------------------------

One important option for that is --opt 'com.docker.network.bridge.enable_ip_masquerade=false', that option disable the MASQUERADE which is enabled as default. After that, You need add iptables rule for POSTROUTING NAT table 

---------------------------------------------------------

iptables -t nat -A POSTROUTING -s 172.20.10.0/24 ! -o my-network-1 -j SNAT --to-source xxx.xxx.xxx.xxx

iptables -t nat -A POSTROUTING -s 172.20.20.0/24 ! -o my-network-2 -j SNAT --to-source xxx.xxx.xxx.xxx

iptables -t nat -A POSTROUTING -s 172.20.30.0/24 ! -o my-network-3 -j SNAT --to-source  xxx.xxx.xxx.xxx

---------------------------------------------------------

After that, You can start Your containers with docker compose command and docker-compose.yml

---------------------------------------------------------
version: '3'

services:
  container1:
    image: nginx
    networks:
      my-network-1:
        
    
  container2:
    image: nginx
    networks:
      my-network-2:
      

  container3:
    image: nginx
    networks:
      my-network-3:
      

networks:
  my-network-1:
    external: true
  my-network-2:
    external: true
  my-network-3:
    external: true
---------------------------------------------------------




That's all.
Bye.




Comments

Popular posts from this blog

Відновлення роботи роботи роутера Linksys WRT54G3G-ST після невдалого обновлення прошивки.

Docker certbor autoreNEW cert cron job

Debian 12 (Proxmox Mail Gateway) and starting mailCow mail service