Paweł Bajorek

Bajorek

Blog

How to Route Docker Traffic Through a Server Behind a Private Network

The Problem

You have two servers:

  • Server A: Sits behind a private network (NAT/firewall). It has internet access and can make outgoing SSH connections.
  • Server B: A public server where you run Docker containers. You want these containers to access the internet through Server A's network.

Why would you want this? Maybe Server A has access to internal resources. Maybe you need traffic to appear from Server A's IP. Maybe Server A is in a specific geographic location you need.

The challenge: Server A is unreachable from the outside. You can't set up a traditional VPN because you can't initiate connections to Server A—only from it.

The Solution

Use an SSH reverse tunnel with a SOCKS proxy. Server A initiates the connection to Server B, but traffic flows backward—from B through A to the internet.

[Docker on B] → [SSH Tunnel] → [Server A] → [Internet]

Step-by-Step Setup

1. Create the Reverse Tunnel

From Server A, run:

ssh -R 1080 user@server-b -N

That's it. This command:

  • Connects from A to B
  • Opens port 1080 on Server B
  • Creates a SOCKS5 proxy that routes traffic back through A
  • -N means "don't run any commands, just keep the tunnel open"

2. Test the Proxy

On Server B, verify it works:

curl -x socks5://localhost:1080 https://ifconfig.me/ip

This should return Server A's public IP, not Server B's.

3. Route Docker Traffic Through the Proxy

The simplest approach—use host networking:

docker run --network=host curlimages/curl -x socks5://localhost:1080 https://ifconfig.me/ip

With --network=host, the container shares the host's network stack. It can reach localhost:1080 directly.

4. Keep the Tunnel Running

The basic SSH command dies if the connection drops. Use autossh to auto-reconnect.

On Server A:

# Install autossh
sudo apt install autossh

# Run persistent tunnel
autossh -M 0 -f -N -R 1080 user@server-b \
  -o ServerAliveInterval=30 \
  -o ServerAliveCountMax=3

Important Notes

Not all apps respect ALL_PROXY. Tools like curl and Python requests do. Many others don't. If your app ignores the proxy variable, you have an option to use proxychains.

Summary

One SSH command gives you a working "reverse VPN" without installing any VPN software. Simple, encrypted, and effective.