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).

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_ip

Alternatively, you can group the flags together:

ssh -fNL 8080:localhost:80 user@remote_server_ip

Once 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.

  1. Find the PID of the active SSH tunnel:

    pgrep -f "ssh -f -N"
  2. Kill the process using the PID found:

    kill <PID>

    Or terminate it directly in one command:

    pkill -f "ssh -f -N"