Connecting to PostgreSQL Inside Kubernetes with pgcli

Connecting to PostgreSQL inside a Kubernetes cluster with pgcli is fast if you know the exact steps and commands. pgcli is a powerful PostgreSQL client that runs in the terminal with autocomplete and syntax highlighting. Combined with Kubernetes port-forwarding, it becomes a simple but precise way to interact with your database without exposing it to the public internet.

First, identify the Pod running PostgreSQL. Replace <namespace> and <pod-name> with your actual values:

kubectl get pods -n <namespace>

Once you have the Pod name, forward a local port to PostgreSQL’s port (default 5432):

kubectl port-forward -n <namespace> <pod-name> 5432:5432

Leave this process running. In another terminal window, run pgcli:

pgcli -h localhost -p 5432 -U <db-user> <db-name>

You will be prompted for the password. This connects pgcli directly to PostgreSQL inside Kubernetes. Autocomplete reduces mistakes. Syntax highlighting keeps queries readable. Because the port-forward only runs while you need it, security is tighter.

For repeated connections, store credentials in environment variables:

export PGUSER=<db-user>
export PGPASSWORD=<db-password>
export PGDATABASE=<db-name>
pgcli -h localhost -p 5432

This removes clutter from your commands, useful in scripting or automation.

Why use pgcli with Kubernetes? It avoids a heavier UI, makes live debugging faster, and keeps tooling lightweight. You don’t need to deploy extra services. You don’t need complex VPN setups. Kubernetes kubectl port-forward is already secure and built-in.

Make sure your local machine has network access to the cluster. If you’re using a remote cluster, connect via your usual Kubernetes authentication flow. Once you are inside, pgcli works as if PostgreSQL runs locally.

Ready to skip complex dashboards and messy tunnels? Try it with hoop.dev — see live Kubernetes access in minutes.