Access a Database from Outside the Cluster

Post-deployment guide

This guide contains instructions on how to connect to a database from outside the cluster using kubectl port-forwarding method.

Prerequisites

  1. Installation and configuration.

The steps to install and configure kubectl to access the Kubernetes Cluster in your machine are given below.

  • Install kubectl.

    sudo snap install kubectl --classic
  • Check the kubectl version.

    kubectl version --client
  • Configure kubectl and create a .kube directory in your home folder.

     mkdir -p $HOME/.kube 
  • Download the kube-config file from Rancher UI.

  • Place the kube-config file in the .kube folder.

    cp /path/to/your/kube-config $HOME/.kube/config
  • Set permissions for the kube-config file.

    chmod 400 $HOME/.kube/config
  • Export the KUBECONFIG environment variable.

    export KUBECONFIG="$HOME/.kube/config" 
  • Verify the configuration.

    kubectl config view
  1. You must have access to the Kubernetes Cluster.

  2. You must have the necessary permissions to perform port-forwarding to the database service in the Kubernetes Cluster.

Procedure

Ensure that the cluster kubeconfig is set on your machine and follow the commands below to connect to the respective database.

  • Get the database services running in the cluster using the command below.

    kubectl get pods -n <namespace of env> | grep postgresql-0 
    ex : kubectl get pods -n dev | grep postgresql-0
  • Confirm the database you want to connect. Perform port-forwarding for the corresponding service using the kubectl command.

    kubectl port-forward pod/<pod-name> <local-port>:<pod-port>
    ex : kubectl port-forward -n dev pod/social-registry-postgresql-0 5432:5432
  • Connect to the database.

    psql -h localhost -p 5432 -U <dbuser> -d <database>

    \

Notes

  • The kubectl port-forward must keep running in the foreground while you are accessing the database.

  • Ensure that your local port (e.g., 5432) is not being used by another service on your local machine.

Last updated

Logo

Copyright © OpenG2P. This work is licensed under Creative Common Attribution (CC-BY-4.0) International license unless otherwise noted.