How to SSH Tunnel to Remote Postgre SQL Container

8 min read.

Sometimes your PostgreSQL runs inside a remote Docker container and is not directly exposed to public internet. In that case, SSH tunneling is the clean and safe way to connect from your local machine.

This guide shows the exact flow with commands you can copy.

Why use SSH tunnel for PostgreSQL

Good reasons:

  • avoid opening database port publicly
  • keep access private through SSH
  • use local tools (psql, DBeaver, Prisma) like normal

The connection path becomes:

local machine -> SSH server -> PostgreSQL container

What you need first

  • SSH access to remote host
  • Docker running on remote host
  • PostgreSQL container name
  • container port (usually 5432)
  • free local port (example 5433)

Optional but recommended:

  • SSH key auth instead of password
  • non-root SSH user if your server allows it

Step 1: Get PostgreSQL container IP

Run this command on your local terminal:

ssh root@<remote_host> "docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <postgre_container_name>"

It should print an internal Docker IP like 172.18.0.5.

If no IP is returned, check container name first:

ssh root@<remote_host> "docker ps --format '{{.Names}}'"

Step 2: Create SSH tunnel

Use this command:

ssh -N -L <local_port>:<postgre_container_ip>:<postgre_container_port> root@<remote_host>

Example:

ssh -N -L 5433:172.18.0.5:5432 root@example.com

Keep this terminal window open while using the DB.

Step 3: Connect from local tools

Now connect using localhost:

  • host: 127.0.0.1
  • port: 5433 (or your chosen local port)
  • username/password/database: same as remote PostgreSQL credentials

For psql example:

psql -h 127.0.0.1 -p 5433 -U <db_user> -d <db_name>

Keep tunnel running in background (optional)

If you do this often, use:

ssh -f -N -L 5433:172.18.0.5:5432 root@example.com

To stop it later, find process and kill:

ps aux | grep "ssh -f -N -L 5433"
kill <pid>

Security tips

  • do not expose 5432 publicly unless really needed
  • prefer SSH keys and disable password login when possible
  • avoid using root for daily tasks if a limited user works

Can I tunnel directly to localhost on remote host?

Yes, if PostgreSQL is bound on host network. But for Docker bridge networks, container IP is often needed.

Can I use this with Prisma?

Yes. Set your Prisma database URL to 127.0.0.1:<local_port> while tunnel is active.

Is autossh required?

Not required for quick work, but useful for long-running stable tunnels.

Latest Posts