On this page
- Why use a tunnel instead of opening the port?
- How do you check the database only listens locally?
- How do you open a tunnel from your computer?
- How do you save tunnels in your SSH config?
- How do you give tunnel access without a shell?
- How do you connect from Python with psycopg?
- How do GUI clients use the tunnel?
- How do you keep a tunnel up all the time?
- Questions
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'inpostgresql.conf - MySQL:
bind-address = 127.0.0.1in/etc/mysql/mysql.conf.d/mysqld.cnf - MariaDB:
bind-address = 127.0.0.1in/etc/mysql/mariadb.conf.d/50-server.cnfor/etc/my.cnf.d/mariadb-server.cnf - MongoDB:
bindIp: 127.0.0.1in/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 adminFor 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 yesssh -N db-tunnelExitOnForwardFailure 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_keysThen 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/nologinsudo sshd -t
sudo systemctl restart ssh # sshd on Rocky/AlmaThe 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, userdeployand your private key. On the Main tab use host127.0.0.1and 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:5433or127.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-pagerThis 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.
More in Databases
- Install MySQL 8
- Install MariaDB
- Install PostgreSQL
- Install MongoDB
- PostgreSQL JSON, arrays and special types
- PostgreSQL views, triggers and CTEs
- PostgreSQL full-text search and encryption
- MySQL keys, indexes and full-text search
- MySQL JSON, views and stored procedures
- Apache Solr search server
- Install Redis or Valkey
- Install Memcached
- Apache Cassandra cluster
- Install Apache CouchDB
- InfluxDB for time series
- Install Elasticsearch
- Back up and restore MySQL and MariaDB
- Back up and restore PostgreSQL
- MySQL users, roles and passwords
- PostgreSQL roles and permissions
- Repair a crashed MySQL table
- PostgreSQL streaming replication
- MongoDB replica set
- PostGIS for location data
- Database insight with PgHero
- Couchbase Server
- ArangoDB multi-model database