How to Use SSH Tunnel with Raspberry Pi: Simple Guide
To use an
ssh tunnel with a Raspberry Pi, run ssh -L local_port:target_host:target_port pi@raspberry_pi_ip from your computer. This command forwards a local port to a port on the Raspberry Pi or another device, enabling secure access through the tunnel.Syntax
The basic syntax for creating an SSH tunnel to your Raspberry Pi is:
ssh -L local_port:target_host:target_port user@raspberry_pi_ip
Explanation:
-L: Specifies local port forwarding.local_port: The port on your computer you want to use.target_host: The host the Raspberry Pi will forward traffic to (oftenlocalhostfor the Pi itself).target_port: The port on the target host you want to access.user: Your Raspberry Pi username (default ispi).raspberry_pi_ip: The IP address of your Raspberry Pi.
bash
ssh -L 8080:localhost:80 pi@192.168.1.100
Example
This example creates an SSH tunnel to access a web server running on the Raspberry Pi's port 80 through your local port 8080.
After running the command, open http://localhost:8080 in your browser to see the Raspberry Pi's web server.
bash
ssh -L 8080:localhost:80 pi@192.168.1.100
Output
Warning: Permanently added '192.168.1.100' (ECDSA) to the list of known hosts.
pi@192.168.1.100's password:
Common Pitfalls
Common mistakes when using SSH tunnels with Raspberry Pi include:
- Using the wrong
local_portthat is already in use on your computer. - Incorrect
target_hostortarget_port, causing the tunnel to fail. - Not having SSH enabled on the Raspberry Pi.
- Firewall or network restrictions blocking the SSH connection.
- Forgetting to keep the SSH session open; closing it will close the tunnel.
bash
Wrong: ssh -L 80:localhost:80 pi@192.168.1.100 # Local port 80 often in use Right: ssh -L 8080:localhost:80 pi@192.168.1.100
Quick Reference
| Option | Description |
|---|---|
| -L local_port:host:port | Forward local port to remote host and port through SSH |
| pi@raspberry_pi_ip | SSH login user and Raspberry Pi IP address |
| localhost | Refers to the Raspberry Pi itself when used as target_host |
| Keep SSH session open | Tunnel works only while SSH connection is active |
Key Takeaways
Use the -L option with ssh to create a local port forwarding tunnel to your Raspberry Pi.
Choose a local port not in use to avoid conflicts.
Ensure SSH is enabled and accessible on your Raspberry Pi.
Keep the SSH session open to maintain the tunnel.
Verify target host and port are correct for the service you want to access.