How to share your local web server to the Internet using a reverse SSH tunnel
I was recently working with integrating Stripe payments with a Django app. Since it's a subscription-based web application, it made a lot of sense for us to use webhooks, which Stripe supports. You basically set a URL in your Stripe account settings where Stripe could POST when an event occurs (eg. trial ends, subscription canceled due to an unpaid invoice, etc.). This eliminates the need of having to poll the Stripe server to check whether certain events have occurred.
This makes testing during development a little harder, though. The web server running on your localhost will need to be accessible over the Internet so Stripe can send the POST request. There are services that solve this problem such as the free localtunnel service. But while I was doing my testing the localtunnel service was down.
So I thought of maybe installing the localtunnel service itself on my own virtual private server running Ubuntu 10.04 on Rackspace. But it turned out there was an even easier way using a reverse SSH tunnel (remote port forwarding).
Setting this up is very easy:
1. Add the following line to /etc/ssh/sshd_config (I just added it at the very end) on your remote SSH server to allow remote port forwarding:
GatewayPorts yes
2. Save the file and apply the changes with:
sudo restart ssh
3. On your local development machine, make sure the localhost web server is running then type the command:
ssh user@www.myremotehost.com -R 8000:localhost:8000
What this basically does is forward port 8000 of the remote host to port 8000 of your local machine. If you're using Django and runserver, for example, the web server runs on port 8000 by default. You can use other ports that are not already in use by other services.
To test simply go to www.myremotehost.com:8000 and you should see your local web server show up.
An even better command is this:
ssh user@www.myremotehost.com -nNT -o ServerAliveInterval=30 -R 8000:localhost:8000
This would run the session in the background and will send a ping every 30 seconds to prevent getting automatically disconnected due to inactivity (source).
This is yet another useful benefit of having your own VPS where you have full access. You can of course use reverse SSH tunneling for services other than web as well (such as giving an outsider remote desktop access to another machine on your LAN at work).
Tags: linux, security, tech, software development, networking