Log inSign up

Connect to your server database safely with SSH tunnels

Leave the database listening on 127.0.0.1 and run ssh -N -L 5433:127.0.0.1:5432 deploy@198.51.100.24 on your own computer; then point any client at 127.0.0.1:5433. The traffic travels encrypted inside SSH, no database port is opened in the firewall, and the same idea works for MySQL, MongoDB, Redis, Python scripts and GUI tools.

Topic: Databases · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

Why use a tunnel instead of opening the port?

A tunnel keeps the database invisible to the internet. Open database ports attract constant password guessing and exploit scans, and many database protocols send data unencrypted unless TLS is configured carefully.

With a tunnel, the only exposed service is SSH, which you have already locked down with keys (see the SSH keys and hardening tutorial). The database keeps its default listen_addresses = 'localhost' or bind-address = 127.0.0.1, and every outside connection must first pass SSH key authentication.

Tunnels suit administrators, reporting scripts and desktop tools. For a permanent link between two servers with heavy traffic, such as replication, a direct TLS connection limited to one peer IP is usually cleaner; the PostgreSQL replication guide shows that pattern.

How do you check the database only listens locally?

List the listening sockets on the server. Each database should be bound to 127.0.0.1 (or ::1), not 0.0.0.0.

sudo ss -tlnp | grep -E "5432|3306|27017|6379"

Expected output shows addresses like 127.0.0.1:5432 and 127.0.0.1:3306. If you see 0.0.0.0 or the public IP, fix the setting:

  • PostgreSQL: listen_addresses = 'localhost' in postgresql.conf
  • MySQL: bind-address = 127.0.0.1 in /etc/mysql/mysql.conf.d/mysqld.cnf
  • MariaDB: bind-address = 127.0.0.1 in /etc/mysql/mariadb.conf.d/50-server.cnf or /etc/my.cnf.d/mariadb-server.cnf
  • MongoDB: bindIp: 127.0.0.1 in /etc/mongod.conf

Restart the service after editing and run ss again. Also make sure no firewall rule opens these ports; sudo ufw status or sudo firewall-cmd --list-all shows the current rules.

How do you open a tunnel from your computer?

Run ssh -L with a free local port, the target address as seen from the server, and your normal login. Linux, macOS and Windows 10 or 11 all include the OpenSSH client.

# PostgreSQL: local 5433 to the server 5432
ssh -N -L 5433:127.0.0.1:5432 deploy@198.51.100.24
# MySQL or MariaDB: local 3307 to the server 3306
ssh -N -L 3307:127.0.0.1:3306 deploy@198.51.100.24
# several at once, in the background
ssh -f -N -L 5433:127.0.0.1:5432 -L 6380:127.0.0.1:6379 deploy@198.51.100.24

-N means no remote command, only forwarding. A local port different from the default avoids clashing with a database you may run on your laptop. In a second terminal, connect as if the database were local:

psql "host=127.0.0.1 port=5433 dbname=shop user=shopapp"
mysql -h 127.0.0.1 -P 3307 -u shopapp -p
mongosh "mongodb://127.0.0.1:27018/?directConnection=true" -u admin

For MySQL, use 127.0.0.1 and not localhost: the client treats localhost as a request for a local socket file and skips the tunnel. For MongoDB, forward 27018 to 27017 first, and keep directConnection=true so the driver does not try to discover replica set members by their public names.

How do you save tunnels in your SSH config?

Put the forwarding in ~/.ssh/config on your computer so a short command opens the same tunnel every time.

Host db-tunnel
    HostName 198.51.100.24
    User deploy
    IdentityFile ~/.ssh/id_ed25519
    LocalForward 5433 127.0.0.1:5432
    LocalForward 3307 127.0.0.1:3306
    ServerAliveInterval 30
    ServerAliveCountMax 3
    ExitOnForwardFailure yes
ssh -N db-tunnel

ExitOnForwardFailure stops ssh with an error if the local port is already taken, instead of silently connecting without the tunnel. The keepalive settings close a dead connection within about a minute and a half so you notice it.

How do you give tunnel access without a shell?

Create a dedicated user that may forward to the database port and nothing else. This is useful for a colleague, a reporting tool or a script that should not be able to log in.

sudo useradd -m -s /usr/sbin/nologin dbtunnel
sudo install -d -m 700 -o dbtunnel -g dbtunnel /home/dbtunnel/.ssh
sudo nano /home/dbtunnel/.ssh/authorized_keys      # paste their public key
sudo chown dbtunnel:dbtunnel /home/dbtunnel/.ssh/authorized_keys
sudo chmod 600 /home/dbtunnel/.ssh/authorized_keys

Then add a block at the end of /etc/ssh/sshd_config:

Match User dbtunnel
    AllowTcpForwarding local
    PermitOpen 127.0.0.1:5432
    X11Forwarding no
    AllowAgentForwarding no
    PermitTTY no
    ForceCommand /usr/sbin/nologin
sudo sshd -t
sudo systemctl restart ssh        # sshd on Rocky/Alma

The user can now run ssh -N -L 5433:127.0.0.1:5432 dbtunnel@198.51.100.24 but gets no shell and cannot forward to any other port. Combine it with a database role that has only the rights they need; the PostgreSQL roles guide and MySQL users guide show how.

How do you connect from Python with psycopg?

Start the tunnel, then connect psycopg to the local end. The simplest robust pattern is to let the script open the tunnel itself with the system ssh client and close it at the end.

python3 -m venv .venv && . .venv/bin/activate
pip install "psycopg[binary]"
import subprocess, time, socket, psycopg

tunnel = subprocess.Popen(["ssh", "-N", "-o", "ExitOnForwardFailure=yes",
                           "-L", "5433:127.0.0.1:5432", "deploy@198.51.100.24"])
try:
    for _ in range(50):
        try:
            socket.create_connection(("127.0.0.1", 5433), timeout=0.2).close()
            break
        except OSError:
            time.sleep(0.2)
    with psycopg.connect(host="127.0.0.1", port=5433, dbname="shop",
                         user="shopapp", password="change-me") as conn:
        row = conn.execute("SELECT count(*) FROM orders").fetchone()
        print("orders:", row[0])
finally:
    tunnel.terminate()

The loop waits until the forwarded port accepts connections before psycopg tries it. Keep the password in an environment variable or a ~/.pgpass file rather than in the code; the Python and pip guide covers virtual environments. The same approach works with PyMySQL or mysqlclient on port 3307.

How do GUI clients use the tunnel?

Most desktop database tools have an SSH tab that builds the tunnel for you; otherwise point them at the local port of a tunnel you opened yourself.

  • DBeaver: in the connection settings, open the SSH tab, enable SSH tunnel, enter 198.51.100.24, user deploy and your private key. On the Main tab use host 127.0.0.1 and port 5432.
  • pgAdmin 4: on the server dialog, the SSH Tunnel tab takes the server address, user and key; set the Connection host to 127.0.0.1.
  • MySQL Workbench: choose the connection method Standard TCP/IP over SSH, fill in the SSH host and key, and set the MySQL host to 127.0.0.1.
  • Any other client: open the tunnel from a terminal and connect to 127.0.0.1:5433 or 127.0.0.1:3307.

Some tools only accept keys in the older PEM format; if a client rejects your key, try a separate key for it rather than weakening the server settings.

How do you keep a tunnel up all the time?

Run it as a systemd user service on the machine that needs it, so it starts at login and restarts after network drops.

mkdir -p ~/.config/systemd/user
cat > ~/.config/systemd/user/db-tunnel.service <<'EOF'
[Unit]
Description=SSH tunnel to the database server

[Service]
ExecStart=/usr/bin/ssh -N db-tunnel
Restart=always
RestartSec=10

[Install]
WantedBy=default.target
EOF
systemctl --user daemon-reload
systemctl --user enable --now db-tunnel
systemctl --user status db-tunnel --no-pager

This reuses the db-tunnel entry from your SSH config, so the key must work without a passphrase prompt (use an agent or a dedicated key). To let it run without an active login on a server, enable lingering with sudo loginctl enable-linger $USER. The autossh package is an alternative that adds its own link monitoring.

Questions about Remote database access over SSH

Is an SSH tunnel slower than a direct connection?

The overhead is small for typical queries. Large exports pay a little for encryption, which is usually worth it compared with an open port.

Do I still need TLS in the database?

Not for tunneled connections, since SSH already encrypts the traffic. Use TLS when another server connects directly over a public address.

Why does the tunnel say the address is already in use?

Something on your computer already listens on that local port, often a local database. Pick another local port such as 5434 or 3308.

Can I tunnel with an SSH key that has a passphrase?

Yes. Load it into ssh-agent once per session, and ssh uses it without asking again.

Does this work for Redis or other databases?

Yes. Any TCP service works the same way, for example ssh -N -L 6380:127.0.0.1:6379 deploy@198.51.100.24 for Redis.