Skip to content

Instantly share code, notes, and snippets.

@int128
Last active January 17, 2024 07:55
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save int128/aecad331dc66b2272bf0 to your computer and use it in GitHub Desktop.
Save int128/aecad331dc66b2272bf0 to your computer and use it in GitHub Desktop.
Transparent proxy for Docker containers

Transparent proxy for Docker containers

If the Docker host is placed inside a proxy server, it needs to add the proxy configuration to each Dockerfile such as ENV http_proxy.

Following allows transparent access from the container to outside without any proxy configuration.

  1. Set up the transparent proxy
  2. Apply iptables rule for the transparent proxy

Note that it solves only http access but not https access.

1. Set up the transparent proxy

Install squid and edit /etc/squid/squid.conf.

2. Apply iptables rule

Create /etc/systemd/system/docker-proxy-dnat.service and start it.

sudo systemctl start docker-proxy-dnat
sudo systemctl enable docker-proxy-dnat

Example: access to www.google.com

curl http://www.google.com/
|
| DNAT rule:
| Rewrites destination of the packet to 172.17.42.1:9090
|
172.17.42.1:9090
|
| Squid:
| Proxies the request to 127.0.0.1:9090
|
127.0.0.1:9090
|
| SSH port forward:
| Forwards the request to your local proxy
|
Your local proxy
|
|
www.google.com
[Unit]
Description=Apply DNAT rule for transparent proxy
After=docker.service
[Service]
Type=oneshot
ExecStart=/usr/sbin/iptables -t nat -A PREROUTING -s 172.17.0.0/16 ! -d 172.17.0.0/16 -p tcp --dport 80 -j DNAT --to 172.17.42.1:9090
ExecStop=/usr/sbin/iptables -t nat -D PREROUTING -s 172.17.0.0/16 ! -d 172.17.0.0/16 -p tcp --dport 80 -j DNAT --to 172.17.42.1:9090
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
acl docker src 172.17.0.0/16
http_access allow docker
http_access allow localhost
http_port 172.17.42.1:9090 intercept
cache_peer 127.0.0.1 parent 9090 0
never_direct allow all
visible_hostname linux
forwarded_for off
request_header_access X-FORWARDED-FOR deny all
request_header_access Via deny all
request_header_access Cache-Control deny all
@andycee
Copy link

andycee commented Oct 18, 2018

After two days of struggle that saves me, thank you!

@anthosz
Copy link

anthosz commented Apr 18, 2019

I just try it locally (without docker, it works (http & https)) but transparent proxy doesn't works (with docker) on my side.

I tried without success these rules:

  1. -s 172.16.0.0/12 ! -d 172.16.0.0/12 -p tcp --dport 80 -j DNAT --to 172.17.0.1:9090
  2. -s 172.16.0.0/12 ! -d 172.16.0.0/12 -p tcp --dport 80 -j DNAT --to 172.18.0.1:9090
  3. -s 172.16.0.0/12 ! -d 172.16.0.0/12 -p tcp --dport 80 -j DNAT --to LAN_IP:9090

@724399396
Copy link

Thanks,very helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment