# Access a server database without opening its port to the internet

> SSH port forwarding lets you use your database app on a remote database safely.

Source: https://fullbytedeveloper.com/blog/sshtunnel
Published here: 2026-11-18, updated 2026-12-03

Keep Postgres listening on the server's localhost (or a private interface) and reach it from your laptop through an SSH local forward [1][3]. One command maps a free local port to the remote database port. Your GUI or psql then talks to localhost; nothing new opens on the public internet.

## Quick start: one forward

On your laptop (ports are examples):

```bash
ssh -N -L 5433:localhost:5432 you@your-server
```

Leave that process running. In another terminal:

```bash
psql -h localhost -p 5433 -U your_db_user your_db
```

Ctrl+C on the ssh process closes the tunnel [1].

What each piece means:

- `-N` means no remote shell command; the session exists only to carry forwards [1].
- `-L 5433:localhost:5432` means "listen on my laptop's 5433, and when something connects, dial `localhost:5432` from the server's point of view" [1].
- Choosing 5433 avoids colliding with a local Postgres on 5432.

The middle host in `-L` is resolved on the remote side. `localhost` there is the server, not your laptop. That is how you reach a database that never bound `0.0.0.0:5432` on the public NIC [1][3].

## Prove the resolve before you dial

Put the forward in a Host block and dump it with `ssh -G` [1][2]:

```bash
mkdir -p /tmp/tunnel-demo
cat > /tmp/tunnel-demo/config <<'EOF'
Host mydb
  HostName 203.0.113.50
  User you
  LocalForward 5433 localhost:5432
EOF
ssh -F /tmp/tunnel-demo/config -G mydb | egrep '^(user|hostname|localforward) '
```

Captured output:

```text
user you
hostname 203.0.113.50
localforward 5433 [localhost]:5432
```

When `localforward` shows the ports you meant, open the session with `ssh -N mydb`. [SSH config Host blocks](/blog/ssh-config) explain first-value-wins if a wildcard also sets `LocalForward`.

## Everyday Host block

```text
Host mydb
  HostName your-server
  User you
  IdentityFile ~/.ssh/id_ed25519
  IdentitiesOnly yes
  LocalForward 5433 localhost:5432
```

```bash
ssh -N mydb
```

Add `ServerAliveInterval 60` under `Host *` if idle NATs drop long tunnels [2]. Keep database auth in place: the tunnel is encrypted transport, not a password replacement [1][3].

<figure>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 260" role="img" aria-label="Laptop localhost:5433 forwards through SSH to server localhost:5432">
  <defs>
    <marker id="sshTunArrow" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto">
      <path d="M0,0 L8,3 L0,6 Z" fill="#14b8a6"/>
    </marker>
  </defs>
  <rect x="0" y="0" width="720" height="260" rx="12" fill="#0b1f3a"/>
  <text x="24" y="36" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="16" font-weight="700">ssh -N -L 5433:localhost:5432</text>
  <rect x="24" y="64" width="200" height="96" rx="8" fill="#123052" stroke="#14b8a6" stroke-width="2"/>
  <text x="36" y="100" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">Laptop</text>
  <text x="36" y="124" fill="#f59e0b" font-family="ui-monospace, monospace" font-size="14">127.0.0.1:5433</text>
  <path d="M224 112 H288" stroke="#14b8a6" stroke-width="3" fill="none" marker-end="url(#sshTunArrow)"/>
  <rect x="296" y="64" width="160" height="96" rx="8" fill="#123052" stroke="#f59e0b" stroke-width="2"/>
  <text x="308" y="100" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">SSH session</text>
  <text x="308" y="124" fill="#cbd5e1" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">encrypted</text>
  <path d="M456 112 H520" stroke="#14b8a6" stroke-width="3" fill="none" marker-end="url(#sshTunArrow)"/>
  <rect x="528" y="64" width="168" height="96" rx="8" fill="#123052" stroke="#14b8a6" stroke-width="2"/>
  <text x="540" y="100" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">Server</text>
  <text x="540" y="124" fill="#f59e0b" font-family="ui-monospace, monospace" font-size="14">localhost:5432</text>
  <text x="24" y="210" fill="#cbd5e1" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">Postgres can stay bound to loopback; no public 5432 required.</text>
</svg>
</figure>

*Local port on the laptop, SSH in the middle, remote loopback database on the far side.*

## Captured forward against a local stub

A tiny HTTP server on `127.0.0.1:18000` stood in for Postgres. Direct curl returned the body. An SSH local forward from port 19000 to that stub, using a key-only login to the same machine, returned the same body through the tunnel:

```bash
# stub already listening on 127.0.0.1:18000
curl -sS http://127.0.0.1:18000/
ssh -i /tmp/tunnel-demo/local_ed25519 -o IdentitiesOnly=yes \
  -N -L 19000:127.0.0.1:18000 ubuntu@127.0.0.1 &
sleep 1
curl -sS http://127.0.0.1:19000/
```

Captured output:

```text
tunnel-ok
tunnel-ok
```

Same pattern on a real VPS: bind Postgres to localhost (see `listen_addresses` in PostgreSQL) [3], open only SSH to the world, and forward. When the ssh process exits, the local port stops accepting connections.

## Security notes that matter

By default the forwarded local port binds to loopback, so neighbors on cafe Wi-Fi cannot use your tunnel [1]. GatewayPorts and remote binds are a different, sharper tool; skip them unless you know you need them.

The tunnel does not invent database credentials. Keep a password or cert on the DB role, and prefer a read-only role for exploratory work [3]. Agent machines that need a private DB should use the same forward pattern instead of exposing 5432; pair with a locked-down SSH key and Host block.

Jump hosts compose cleanly: `ProxyJump bastion` on the Host that also sets `LocalForward` so one alias opens the hop and the port [2]. Confirm with `ssh -G` that both `proxyjump` and `localforward` appear before you rely on it at 1 a.m.

## Mistakes that open the wrong door

Using `-L 5432:localhost:5432` while local Postgres already owns 5432, then blaming the server when bind fails. Pick a free local port.

Writing `-L 5433:127.0.0.1:5432` but expecting the target to resolve on the laptop. The host:port after the first colon is remote-side [1].

Opening security-group port 5432 "just for today" and leaving it open. The tunnel exists so you can leave that port closed.

Forgetting `-N` and exiting the remote shell, which tears down the forward when the session ends.

## Multiple forwards and other ports

One Host block can list several `LocalForward` lines: Postgres on 5433, Redis on 6379, and a private HTTP admin on 8080, each mapped to a free local port [2]. Keep the local ports unique. `ssh -G` prints every `localforward` line so you can spot a collision before bind fails.

Remote forwards (`-R`) and dynamic SOCKS forwards (`-D`) solve different problems. This page stays on `-L` / `LocalForward` because that is the pattern for "my GUI on the laptop, database on the server loopback" [1]. Reach for `-D` when you need a general proxy through the bastion, not when you only need one database port.

Autossh or a systemd user unit can restart a long-lived tunnel after a laptop sleep. Start simple with a manual `ssh -N`; add a supervisor only after you confirm the Host block and DB credentials.

## What Postgres should listen on

Set `listen_addresses` so the database is not on the public interface if SSH is your access path [3]. Many images default to localhost already; cloud security groups that still allow 5432 from `0.0.0.0/0` undo that. Close the security-group hole even when you use a tunnel, so a mistaken bind later does not expose the port.

App servers on the same private network can keep talking to Postgres over the private interface while your laptop uses SSH. The tunnel is for operators and agents, not a replacement for VPC plumbing between services.

## Agents and automation

Coding agents on your laptop that need a staging database should inherit the same `ssh -N` session you already opened, pointing their connection string at `localhost:5433`. Do not teach the agent to open a public DB URL "because the forward is hard." If the agent runs on a remote VM, give that VM its own SSH key and Host block with `LocalForward`, not a world-open security group.

Combine with `IdentitiesOnly yes` and a dedicated key so the tunnel cannot accidentally offer your GitHub key to the database host [2].

## Troubleshooting bind and auth

If ssh exits immediately with a message about the local port already in use, something on the laptop still owns that port. `ss -ltn` (or `lsof -iTCP:5433 -sTCP:LISTEN`) shows the occupant. Pick another local port and update both the Host block and your connection string.

If the tunnel stays up but psql times out, the remote side of the forward is wrong: wrong host in the `LocalForward` target, Postgres not listening, or security rules blocking even loopback on a locked-down host. From an interactive `ssh you@your-server` session, check `ss -ltn` on the server for `5432` and confirm `listen_addresses` [3].

Permission denied on the SSH hop is not a database problem. Fix the key and Host block first with `ssh -G` and a plain `ssh mydb` shell, then add `-N` back [1][2].

## When the tunnel is enough

`ssh -G mydb` shows the forward, `ssh -N mydb` stays up, and `psql -h localhost -p 5433` authenticates with your DB user. No public database port, no VPN appliance required for a single admin laptop. Put the Host block in your config and stop retyping the long `-L` line [1][2].

For key type cut-overs that break GitHub SSH, see [GitHub says invalid signature? Your key type may be the problem](/blog/gh-ssh-rsa). Browse the [Dev tools topic](https://fullbytedeveloper.com/blog/topic/dev-tools).

Send this to the friend who opened their database port to the internet just to connect from home.

Image: A dark public expanse with a closed port on a remote wall, a private database cube hidden behind it, and a teal tunnel carrying a local port-forward loop from a small laptop slab to that cube while the public port stays shut, with no typography or logos.
https://fullbytedeveloper.com/media/sshtunnel/sshtunnel-venice.webp
Forward a local port over a shell tunnel instead of opening the database to the internet.

## Sources

1. [OpenBSD man: ssh](https://man.openbsd.org/ssh)
2. [OpenBSD man: ssh_config](https://man.openbsd.org/ssh_config)
3. [PostgreSQL docs: listen_addresses](https://www.postgresql.org/docs/current/runtime-config-connection.html)
