I have a problem when using ssh port forwarding and nat simoultaneously.


Machine A runs a webserver on port 8080 Machine B is a raspberry pi which works like a little router. It has two network interfaces (eth0 and eth1). eth0 is connected to the LAN and through that to the WAN. eth1 is only connected to Machine A. It runs ddclient for dyndns connection.


I want to connect to machine A safely to port 8080 etc. through ssh port forwarding.

What I tried:

On my local machine (MacBook) I used:

ssh -L 5903: pi@pi.dynip.org


ssh -L 5903: pi@machine-b-ip

and I can connect to the vnc server on machine B with (just for testing purposes):


So my assumption was to forward port 8080 from my local machine to machine B and "nat" it to machine A with this iptable rules:

iptables -t nat -A POSTROUTING --out-interface eth1 -j MASQUERADE
iptables -A FORWARD --in-interface eth0 -j ACCEPT
iptables -t nat -A PREROUTING -p tcp -i eth0 -m tcp --dport 8080 -j DNAT --to-destination

My other iptables config was:

iptables -t nat -A PREROUTING -p tcp -i eth0 -m tcp --dport 9090 -j DNAT --to-destination
iptables -t nat -A POSTROUTING --out-interface eth1 -j MASQUERADE
iptables -A FORWARD --in-interface eth0 -s -j ACCEPT
iptables -A FORWARD --in-interface eth0 -j DROP

I also enabled ssh GatewayPorts on machine B but every time I want to connect through:

I get the error "connection refused" and the log says that "this service is not running". But if I connect through:


it works.

Can you help me, please? I tried several solutions from remote and local ssh port forwarding, over ssh multi hops and nat etc. but wasn't able to get a working solution for me.

Thanks in advance, Dominik.


You Should not need all the Iptables rules to route to your second box. you can do a similar thing to what you are doing with your VNC connection

ssh ssh -L 8081:192.168.x.x:8080 pi@pi.dynip.org

Where 192.168.x.x is the IP address of Machine A

Then you can open a web browser on your local machine and connect to


This will allow you connect to the internal website and the routing will be handled by ssh. Your local port of 8081 will be forwarded over ssh to the ssh server. the server will then send the request to MachineA on port 8080

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.