Run SSH Port Forwarding in Background Ubuntu
This article explains how to run an SSH port forwarding command in
the background on Ubuntu Linux. You will learn the specific command-line
flags required to keep your secure tunnel active without keeping your
terminal window occupied, focusing on the essential -f and
-N flags.
To run an SSH port forwarding command in the background on Ubuntu
Linux, you use the -f flag.
The Key Flags Explained
When setting up a background SSH tunnel, the -f flag is
almost always combined with the -N flag and your port
forwarding choice (such as -L for local forwarding).
-f: This flag tells the SSH client to go to the background just before command execution. It asks for passwords or passphrases before sending the process to the background.-N: This flag instructs SSH not to execute a remote command. This is extremely useful for port forwarding because you only want to secure the connection, not open an interactive shell session.-L: This flag specifies the local port forwarding configuration (e.g.,local_port:destination_host:destination_port).
Example Command
To forward local port 8080 to port 80 on a
remote server, running the process entirely in the background, use the
following syntax:
ssh -f -N -L 8080:localhost:80 user@remote_server_ipAlternatively, you can group the flags together:
ssh -fNL 8080:localhost:80 user@remote_server_ipOnce you execute this command, SSH will prompt you for your password (if you are not using SSH keys), establish the connection, and immediately return you to your local prompt. The tunnel will continue to run silently in the background.
How to Stop the Background Tunnel
Since the tunnel runs in the background, closing the terminal window will not always terminate the connection. To stop the background SSH port forwarding process, you must find its Process ID (PID) and terminate it.
Find the PID of the active SSH tunnel:
pgrep -f "ssh -f -N"Kill the process using the PID found:
kill <PID>Or terminate it directly in one command:
pkill -f "ssh -f -N"