Have you ever wanted to share your localhost application with others on the internet? Using a cloud server as a reverse proxy is a secure and effective way to do this. To make it even smoother, you can set up SSH key-based authentication for auto-login. Here’s how.
Prerequisites
- A localhost application running on your machine (e.g., at http://localhost:8080).
- Access to a cloud server with a public IP and Apache2 installed.
- SSH access to the cloud server.
Step 1: Generate an SSH Key for Passwordless Login
On your local machine:
Generate an SSH key pair (if you don’t already have one):
ssh-keygen -t rsa -b 4096 -C "maheshpalamuttath@gmail.com"
- Press Enter to accept the default location (~/.ssh/id_rsa).
- Leave the passphrase blank for passwordless access.
- Copy the public key to your cloud server:
ssh-copy-id mahesh@139.84.139.31
Replace mahesh and 139.84.139.31 with your cloud server's username and IP.
If ssh-copy-id isn’t available, manually copy the key:
cat ~/.ssh/id_rsa.pub
Paste it into the ~/.ssh/authorized_keys file on the cloud server.
Step 2: Establish an SSH Tunnel
Create a reverse tunnel from the cloud server to your local application:
ssh -R 9000:localhost:8080 mahesh@139.84.139.31
Replace 9000 with an available port on the cloud server.
The traffic on the cloud server's localhost:9000 will forward to your local machine's localhost:8080.
Step 3: Configure Apache2 as a Reverse Proxy
On your cloud server:
Enable Apache's proxy modules:
sudo a2enmod proxy proxy_http
sudo systemctl restart apache2
Create a virtual host configuration:
sudo nano /etc/apache2/sites-available/myapp.conf
Add the following:
<VirtualHost *:80>
ServerName library-staff.mydomain.com
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:9000/
ProxyPassReverse / http://127.0.0.1:9000/
</VirtualHost>
Replace library-staff.mydomain.com with your server's public IP or domain.
Enable the site and reload Apache:
sudo a2ensite myapp.conf
sudo systemctl reload apache2
Step 4: Automate the SSH Tunnel
To ensure the tunnel starts automatically after reboot:
Install autossh on your local machine:
sudo apt install autossh
Add the following to your crontab:
crontab -e
Add this line to start the tunnel on boot:
@reboot autossh -M 0 -R 9000:localhost:8080 mahesh@139.84.139.31
Step 5: Secure the Connection with HTTPS
To secure the reverse proxy:
Install Certbot:
sudo apt install certbot python3-certbot-apache
Obtain a free SSL certificate:
sudo certbot --apache -d library-staff.mydomain.com
Now your application is accessible at library-staff.mydomain.com.
Conclusion
With SSH key-based authentication, a reverse SSH tunnel, and Apache2 acting as a reverse proxy, your localhost application is now securely accessible on the internet. Automating the SSH tunnel ensures the setup remains active after reboots, making this a reliable solution for sharing your application with the world.