By @akash_dathan
Connect to a DB hosted in Kubernetes
In production, DBs are not usually hosted in Kubernetes, but there might be some use cases for Dev or mock environments where DBs are hosted inside Kubernetes. Let’s see how er can connect to this DB using CLI or any Database tools like Datagrip, Dbeaver etc…
Contents
The approach I am going to be using will be port forwarding. Since SSH or SSL connection methods are not supported yet,
port forwarding is the way to go for now. So when I say port forwarding, I will be forwarding the 5432
port of my local
machine to the 5432
port of the Kubernetes pod. So, any request to my local 5432
port will be redirected to the 5432
port
of the pod in Kubernetes. So, once the port forwarding is in place just connect to the DB pointing to localhost and 5432
port.
5432
is the post in the pod where Postgres is hosted5432
is the port where the Postgres is hosted, if you are using another port, use that port accordingly- Any available local port can be used to forward to the pod (ones which are not restricted by the OS)
Connect from CLI
Use the following command to forward the port from the CLI. I am assuming that you are already connected to Kubernetes from
your local machine, ie kubectl
is already configured.
kubectl --kubeconfig=/Users/<usernamer>/.kube/config port-forward <pod-name> --namespace=<namespace> 5432:5432
- You can get the pod name using the command
kubectl get pods
- You can add this command to your boot script so that it is run when your machine is powered on
- Alternatively, you can create an alias for this command so that you can forward the port by running a short alias command.
Once the port is forwarded, just go ahead and connect to the DB by using the hostname as localhost
and the port as
5432
(or the port you have specified in the forwarding command)
Connect from Webstorm or Datagrip
Since I use Webstorm, the following is the config I use, I find this optimal. Basically, I add the port forwarding command
in the Startup Tasks
config in Webstorm, so that whenever I open my project the startup task is run and the port is
automatically forwarded.
Startup Tasks
can be found in Settings > Tools > Startup Tasks

Following is the configuration I use in Startup Tasks

- Script text: The port ford command
kubectl --kubeconfig=/Users/<usernamer>/.kube/config port-forward <pod-name> --namespace=<namespace> 5432:5432
- Working directory: Path of the project
Execute in terminal
enabling this would result in a terminal window popping up every time I open this project. I recommend leaving this unchecked, you will be able to see the status in the run options on the top right.
Once the port is forwarded, just go ahead and connect to the DB by using the hostname as localhost
and the port as
5432
(or the port you have specified in the forwarding command)
That’s all folks, happy hacking 🙌