Tunnel between machine and VPS with port forwarding

Abstract: Create a secure SSH tunnel to access remote services without exposing ports to the public internet.

Created: 2026-09-12 by
You can create a secure tunnel between your local machine and a VPS using SSH port forwarding. This method encrypts traffic, allowing you to access remote services securely from anywhere without exposing ports directly to the public internet. By configuring specific SSH flags, you establish a reliable encrypted channel for sensitive data transmission.

Understanding SSH Port Forwarding

Secure Shell (SSH) provides built-in mechanisms for creating tunnels. The most common form is dynamic port forwarding, which acts like a SOCKS proxy. This allows applications on your local machine to route their traffic through the encrypted SSH connection to the VPS. Another variant is local port forwarding, where a specific local port is forwarded to a destination host accessible from the VPS. Both methods leverage the existing SSH infrastructure, meaning you only need SSH access to your server to enable these features.

Dynamic forwarding is particularly useful for browsing the web securely or routing multiple application connections through a single tunnel. Local forwarding is ideal for accessing database servers or internal web interfaces that are not publicly routable but are reachable from the VPS. Understanding the distinction helps in choosing the right configuration for your security needs.

Setting Up Dynamic Port Forwarding

To establish a dynamic tunnel, you use the -D flag with the SSH command. This creates a listening socket on your local machine. Any application configured to use this socket as a proxy will have its traffic encrypted and sent through the VPS. For example, running the following command opens a local port:

ssh -D 1080 user@your_vps_ip

In this command, 1080 is the local port number. You can choose any available port above 1024. The user should be replaced with your actual username on the VPS, and your_vps_ip with the server's address. Once connected, your terminal session remains active, maintaining the tunnel. To configure a browser or other software, set the proxy settings to socks5://127.0.0.1:1080.

This setup ensures that all traffic from the application is routed through the VPS. It effectively masks your real IP address from the destination servers, providing privacy and security. However, note that this requires manual configuration of each application you wish to protect.

Configuring Local Port Forwarding

Local port forwarding maps a local port to a remote host and port. This is useful when you need to access a service running on the VPS or another machine reachable from it. Use the -L flag for this purpose. The syntax is:

ssh -L local_port:remote_host:remote_port user@vps_ip

For instance, if you want to access a MySQL database running on port 3306 on the VPS, you would run:

ssh -L 3307:localhost:3306 user@vps_ip

This forwards local port 3307 to port 3306 on the VPS. You can then connect to localhost:3307 on your machine to interact with the database securely. This method is less flexible than dynamic forwarding but is simpler for specific services. It avoids the overhead of managing proxy settings for every application.

You can also forward multiple ports by adding multiple -L flags. This allows you to aggregate several services into a single SSH connection. Each forwarded port operates independently within the same encrypted tunnel.

Advanced Configuration and Security

For persistent tunnels, consider using autossh, which monitors the SSH connection and restarts it if it drops. This is crucial for long-running tasks or automated scripts. Install autossh via your package manager and replace the ssh command with autossh in your commands. This ensures reliability without manual intervention.

Additionally, you can configure SSH client options in ~/.ssh/config to simplify repeated connections. Define aliases for your VPS with specific forwarding rules. This eliminates the need to remember complex command-line arguments. For example:

Host myvps
    HostName vps.example.com
    User admin
    DynamicForward 1080

With this configuration, simply running ssh myvps establishes the dynamic tunnel automatically. This approach enhances usability while maintaining security standards. It also reduces the risk of typos in long commands.

Consider restricting SSH access to key-based authentication only. Disable password logins in the server configuration to prevent brute-force attacks. This adds an extra layer of security to your tunnel. Combined with firewall rules on the VPS, it creates a robust defense against unauthorized access.

If you need more advanced routing capabilities, look into related guides on Securely Accessing the Internet via 2-Hops WireGuard VPN on Windows 11 and Two VPS Servers for multi-layered encryption strategies. These methods complement SSH tunnels by providing network-level isolation.

Troubleshooting Common Issues

If the tunnel fails to connect, verify that the SSH service is running on the VPS. Check for firewall rules blocking port 22 or the specified local port. Ensure that no other application is already using the local port you intend to forward. On Linux, use netstat or ss to check port availability.

Connection timeouts may occur due to idle sessions. Configure ServerAliveInterval in your SSH client config to send keep-alive packets. This prevents intermediate firewalls from dropping the connection. Set it to a value like 60 seconds to maintain stability.

For performance issues, consider compressing the SSH stream with the -C flag. This reduces bandwidth usage at the cost of CPU cycles. It is beneficial for slow connections or high-latency links. Evaluate the trade-off based on your network conditions.

Frequently Asked Questions

Can I use SSH port forwarding on Windows?

Yes, modern versions of Windows include OpenSSH clients that support port forwarding. Use the same command-line syntax as on Linux. Alternatively, third-party tools like PuTTY offer graphical interfaces for configuring tunnels. Both methods provide equivalent functionality and security.

Is SSH port forwarding faster than a VPN?

SSH tunnels generally have lower overhead than full VPN setups because they encrypt only specific traffic. However, they lack the network-level integration of a VPN. For simple service access, SSH is often faster and easier to configure. For comprehensive network masking, a VPN might be preferable.

How do I close an SSH tunnel securely?

Simply terminating the SSH process closes the tunnel. If using autossh, stop the service to ensure clean disconnection. Avoid force-killing processes to prevent orphaned sockets. Always verify that the local port is no longer in use after closing.

What are the risks of exposing local ports?

Exposing local ports to the network can allow unauthorized access if not properly secured. Restrict bindings to localhost to limit access to your machine. Use strong authentication and encryption keys to mitigate risks. Regularly audit open ports for vulnerabilities.

Can I forward UDP traffic with SSH?

Standard SSH port forwarding supports TCP only. For UDP traffic, you need additional tools or protocols. Some implementations offer experimental UDP support, but it is not universally available. Consider using WireGuard or IPSec for UDP-based tunneling needs.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More