SSH LocalForward in Ubuntu Linux Explained

This article explains the LocalForward option in the Ubuntu Linux SSH client configuration. You will learn what local port forwarding is, how the LocalForward directive works to secure network traffic through an SSH tunnel, and how to configure it for practical use cases like accessing remote databases or internal web services.

The LocalForward option in the SSH client configuration file (~/.ssh/config or /etc/ssh/ssh_config) is used to set up local port forwarding. This mechanism allows you to forward a port from your local Ubuntu machine to a port on a remote server, or to a different machine accessible from that remote server. All traffic sent to the designated local port is securely encrypted and routed through the established SSH connection.

This option is primarily used to bypass firewalls, access services that only accept local connections (such as databases listening on 127.0.0.1 on the remote server), or secure otherwise unencrypted protocols. By tunneling the traffic over SSH, you eliminate the need to expose sensitive ports directly to the public internet.

To configure LocalForward, you add the directive under a specific host block in your SSH configuration file. The standard syntax is:

LocalForward [local_bind_address:]local_port destination_host:destination_port

For example, if you want to access a remote PostgreSQL database running on port 5432 of a server, but the database is configured to only accept local connections, you can define the forward in your ~/.ssh/config file:

Host remote-database
    HostName example.com
    User ubuntu
    LocalForward 5432 localhost:5432

Once you connect to remote-database via SSH, any traffic sent to localhost:5432 on your local Ubuntu machine will be securely tunneled and forwarded to localhost:5432 on the remote server.

Configuring LocalForward in your configuration file is the permanent, reusable equivalent of using the -L flag in the command-line SSH command (for example, ssh -L 5432:localhost:5432 user@example.com). Utilizing the configuration file simplifies your workflow by automating this port-forwarding setup whenever you initiate the connection.