Skip to content

Instantly share code, notes, and snippets.

@Gaarv
Forked from int128/README.md
Created August 5, 2021 09:00
Show Gist options
  • Save Gaarv/3e30a82bdc7238c03205ff8eacc50ff9 to your computer and use it in GitHub Desktop.
Save Gaarv/3e30a82bdc7238c03205ff8eacc50ff9 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment