How to forward a local port with SSH

Local port forwarding helps reach a service that is only accessible from an SSH gateway, such as a private web console or database listener on the remote side. The local machine opens a loopback port, and normal client tools connect to that local address instead of reaching across the private network directly.

OpenSSH uses the -L option to map a local listener to a target host and port from the gateway's point of view. The optional bind address controls who can connect to the local listener, while the target host is resolved by the remote SSH server after authentication.

With the default client policy, omitting the bind address keeps the forwarded port on loopback, such as localhost:8080. Binding to 0.0.0.0 or another LAN address can share the tunnel with other systems, but it also publishes the remote service through the local host, so leave the bind address loopback unless that exposure is intentional and filtered.

Steps to forward a local port with OpenSSH:

  1. Confirm that the target service responds from the SSH gateway.
    $ ssh \
      user@host \
      curl -sS http://localhost/
    internal service reached

    The target host in an -L forward is reached from the SSH gateway, so localhost:80 means the gateway's loopback address, not the local machine.

  2. Start the local port forward in a dedicated terminal.
    $ ssh -N \
      -L 8080:localhost:80 \
      user@host

    -N keeps the session dedicated to forwarding. Add -o ExitOnForwardFailure=yes for scripts or backgrounded tunnels so ssh exits when the listener cannot be created.

  3. Request the forwarded service from another local terminal.
    $ curl -sS \
      http://localhost:8080/
    internal service reached

    A response through localhost:8080 proves the local client reached the target service through the encrypted SSH session.

  4. Use a different local port when 8080 is already in use.
    $ ssh -N \
      -L 18080:localhost:80 \
      user@host

    The local port is the listener on the client. The target port remains 80 because the service on the gateway side did not move.

  5. Allow other trusted hosts to use the local listener only when sharing is intentional.
    $ ssh -N -g \
      -L 8080:localhost:80 \
      user@host

    -g allows remote hosts to connect to local forwarded ports. Pair it with host firewall rules or keep the listener private.

  6. Stop the tunnel by pressing Ctrl-C in the terminal running the ssh -N -L command.

    Closing the SSH session removes the local listener and stops new connections through the forward.