To forward your local service port to your VPS, you can use tools like SSH tunneling, or more advanced options like iptables
for port forwarding. Here’s a step-by-step guide for both methods:
Method 1: SSH Tunneling
Local Port Forwarding
This method forwards a port from your local machine to a port on your VPS.
-
SSH into your VPS with port forwarding:
ssh -L [local_port]:localhost:[remote_port] [user]@[vps_ip]
- Replace
[local_port]
with the port on your local machine you want to forward. - Replace
[remote_port]
with the port on the VPS you want to connect to. - Replace
[user]
with your VPS username. - Replace
[vps_ip]
with your VPS IP address.
Example:
ssh -L 8080:localhost:80 user@vps_ip
This command forwards port 8080 on your local machine to port 80 on the VPS.
- Replace
Remote Port Forwarding
This method forwards a port from your VPS to a port on your local machine.
-
SSH into your VPS with remote port forwarding:
ssh -R [remote_port]:localhost:[local_port] [user]@[vps_ip]
- Replace
[remote_port]
with the port on the VPS you want to forward. - Replace
[local_port]
with the port on your local machine you want to connect to. - Replace
[user]
with your VPS username. - Replace
[vps_ip]
with your VPS IP address.
Example:
ssh -R 8080:localhost:80 user@vps_ip
This command forwards port 8080 on the VPS to port 80 on your local machine.
- Replace
Method 2: Using iptables
for Port Forwarding
On the VPS
-
Enable IP forwarding:
sudo sysctl -w net.ipv4.ip_forward=1
-
Configure
iptables
to forward traffic:sudo iptables -t nat -A PREROUTING -p tcp --dport [vps_port] -j DNAT --to-destination [local_ip]:[local_port] sudo iptables -t nat -A POSTROUTING -j MASQUERADE
- Replace
[vps_port]
with the port on your VPS. - Replace
[local_ip]
with your local machine’s IP address. - Replace
[local_port]
with the port on your local machine.
Example:
sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.100:80 sudo iptables -t nat -A POSTROUTING -j MASQUERADE
- Replace
On Your Local Machine
Ensure that your local firewall allows connections from the VPS.
- Allow incoming connections on the forwarded port:
sudo iptables -A INPUT -p tcp --dport [local_port] -j ACCEPT
- Replace
[local_port]
with the port you are forwarding.
- Replace
Additional Tools
For more advanced scenarios, you might consider using tools like:
- FRP (Fast Reverse Proxy): An open-source reverse proxy that can help you expose a local server to the internet.
- Ngrok: A service that creates secure tunnels to your localhost.
These tools provide more features and flexibility, especially if you need to forward multiple ports or deal with complex networking scenarios.