Deploy and Manage PostgreSQL on Kubernetes
Tags: kubernetes, postgres
Published: 2021-04-01 15:37:42

---
title: Deploy and Manage PostgreSQL on Kubernetes
published: true
description: Utilizing Kubernetes to deploy a PostgreSQL instance allows users to leverage the strengths of both platforms. This article discusses how to easily deploy a PostgreSQL pod in Kubernetes.
tags: kubernetes, postgresql, 
//cover_image: https://direct_url_to_image.jpg
---
PostgreSQL database is an enterprise-grade, open-source object-relational database system focused on providing a highly scalable and robust platform while conforming to SQL standards. Kubernetes is an open-source container orchestration platform designed to be easily deployable in any environment. It enables users to easily deploy and manage containerized applications.

Utilizing Kubernetes to deploy a PostgreSQL instance allows users to leverage the strengths of both platforms. Furthermore, it enables users to create a highly portable and scalable PostgreSQL instance in a Kubernetes cluster. In this article, we will discuss how to easily deploy a PostgreSQL pod in Kubernetes.

## What options are available to deploy PostgreSQL?

When it comes to deploying PostgreSQL on Kubernetes, there are two options. One is to create a Kubernetes deployment from scratch, and the other is to use a helm chart to carry out the deployment.

### Option 01 - Creating deployment configuration from scratch

This option requires the user to set up the ConfigMaps, create and set up persistent storage volumes and then create the PostgreSQL deployment and service. This process involves a higher degree of planning and technical knowledge to get the service up and running. Therefore, only use this option if you have specific requirements that require custom configurations from the ground up.

Therefore, only use this option if you have specific requirements that require custom configurations such as complex persistent storage configurations, network and security policies, multi cluster connectivity etc...

### Option 02 - Use a helm chart

Helm charts can be considered a type of package that can be used to easily deploy applications to Kubernetes clusters. These charts can be used in any kind of deployment, from a single pod application to complex applications consisting of multiple pods with different software and services.

In this article, we will focus on using a helm chart to deploy a PostgreSQL instance. Before that, we should know what Helm is and how to configure Helm in a development environment.

# What is Helm?
Helm is considered as the package manager for Kubernetes. It is an open-source project started with the goal of providing a more efficient way to manage Kubernetes YAML files created when deploying an application.

Currently, Helm has evolved into a fully-fledged package manager that streamlines the installation, upgrading, dependency management, and configuration of applications on a Kubernetes cluster using simple CLI commands (Helm Client).

## Helm Architecture
Helm creates packages by creating helm charts that bundle one or more Kubernetes manifests (YAML files). These charts contain all the dependencies of the project and allow users to deploy an application with a single command. Additionally, charts can be versioned so that users can create different configurations for the same helm chart under different versions. 

## Helm is composed of three main concepts

-   Chart - Contains Information required to create an application instance in Kubernetes 
-   Config - Contains the configuration information that can be merged with a chart to create a releasable object.
-   Release - A running instance of a chart, combined with a specific config.
    
Helm executable can be broken down into two components as follows;

-   The Helm Client: A command-line tool used by end-users to create and manage helm charts and interfaces with the Helm library.
    
-   The Helm Library: Interfaces with the Kubernetes API and executes all the helm operations.
    
Both of these are written in the Go programming language. To connect with Kubernetes, Helm utilizes the Kubernetes client library using REST API.

## How to Install Helm

Before installing Helm, we need to have a Kubernetes cluster configured and running. It is recommended to use the latest stable release of Kubernetes.

Installing Helm is a simple process. You can use a package manager like Homebrew for Mac, Chocolatey/Scoop for Windows, or apt/Snap for Debian/Ubuntu. Another way to install Helm is by downloading the [binary](https://github.com/helm/helm/releases/tag/v3.5.3) for the related operating system.

The following example demonstrates how to install Helm using the chocolatey package manager in a windows environment.

`choco install kubernetes-helm`

RESULT
![](https://lh5.googleusercontent.com/f-11Tpa0gxoJJpsVvcr1T0NJFg8_QpQjVNH1_lggdIy2NpDktX2LzpzZxvZFLNjKPfOUnWDQsZ9KCVBChEc2cJUEByKci6kc-LgW1THHcXZdW8Q_ESYRlukLvzcaxIH3MT-4MBY)

That’s it, and you have completed installing Helm. Next, let’s verify the installation by checking the helm version using the command below.

`helm version`

RESULT
![](https://lh4.googleusercontent.com/-EYWdzKyzneOdqwqTgu1_yCaAg9Gp3bnBG4k5HeoOJB3WE30WNDGLS2VlxgH5IvTj-7gAW8kYN36AwVyHRZNg0PKJwH-qaqhpVUyStO7dSgVIPVmtOY465H8PLGw0zfjldr-tO0)

## Finding Helm Charts
You have the option to create helm charts from scratch. However, there are also prebuilt charts that can be deployed instantly for popular software like PostgreSQL. There, Helm charts are stored and shared using a chart repository.

[Artifact Hub](https://artifacthub.io) is the official distributed community Helm chart repository. For third-party repositories, we need to add the repository to our local environment before we can use it.

### Available PostgreSQL charts

First, we have to find a suitable PostgreSQL helm chart for deployment. For that, we can search the Artifact Hub using the following command in the CLI interface.

`helm search hub postgresql`

RESULT
![](https://lh6.googleusercontent.com/Yn4ZxNK6ZgMKzXzpXX1KfJz3ndPS2gWNU5R3ASEJ0jOrLpvuOwtcBCR5ohiqnAc0mUO1Nl52u0sO8qHXG5gy-3xI5G-cdNexOXvc-E6wa0umrUis_yRmYxuaZKlK3g46uF5pioE)

The above command will search for all the available charts in the Artifact Hub for a PostgreSQL chart. The “hub” parameter points to the Artifact Hub.

To search in a third-party repository, first, we need to add the repository to our helm installation. It can be done through the “repo add” command. The following example shows how to add the bitnami repository to our helm installation and search for the repository.

`helm repo add bitnami https://charts.bitnami.com/bitnami`  
`helm search repo bitnami`

RESULT
![](https://lh5.googleusercontent.com/EfTcEKBh5XMxGjHR0wFau10it1kbr5K2bUlJH_TPuvVz6snYyzn9f4Z5CeVUWyq1t9DagP6Mou8bcGArJkcgp01BFgnfIou490FiM3S6ir8XDPaNz_9UuVb81KW1KxIwQmtd8GY)

In the above search command, we use the parameter “repo” to carry out the search in the newly added repository apart from the artifact hub. Now let’s search for PostgreSQL instances in this repo using the following command.

`helm search repo postgresql`

RESULT
![](https://lh5.googleusercontent.com/p96C4iHaDCa8uBhWs7-gL0nmF7aU8suD8xHiRL8aH942pi5nKI5acDKz8vhVw6rHzlsvRu0GDZmry3LXTqmXwb6VJPLEhXZ7vmWW2rvh9ODMPH5Ue_QVeASJRPj0A_PrLGL8egg)

  
## Installing Helm Charts
By now, we have located a helm chart, and the next step would be to install the chart using the “helm install command,” as shown below.

Syntax
`helm install <Pod Name>  <Chart Name>`

Code
`helm install postgresql-dev bitnami/postgresql`

RESULT
![](https://lh5.googleusercontent.com/CGubGKLo__04fCiXV52yw5hDiaGxkxNPn_rnahAj7M476PJnNS43CHTz30yx5mx-VdgWysWdiUXqG1qbBwc9EwA33i4zfirqO6v0rDRy5OVJIf2LrwYBGun-fboJRE8uTLJASS0)

Wait till the installation is completed. Then, check the Kubernetes environment, and you will see that a PostgreSQL instance has been deployed successfully.

`kubectl get all`

RESULT
![](https://lh3.googleusercontent.com/KePRg-FqAk82-FBTPJbDeA6cm5LMvPXFcnSi_vfTSie-oPwJ_LX5x7Zex_yrxF0-jU574gspZfph9ljjjnwYH_6q41zGS6mYMauZphrFscNF_Iv7LdGhkG04NklOziFgNgVDMT8)

Now we have deployed a PostgreSQL container. The next step would be to connect to the database, and it can be done using the following commands.

We need to extract the password of the instance and save it as an environmental variable. That password will be used to create the connection.

`export POSTGRES_PASSWORD=$(kubectl get secret --namespace default postgresql-test -o jsonpath="{.data.postgresql-password}" | base64 --decode)`
  
`kubectl run postgresql-test-client --rm --tty -i --restart='Never' --namespace default --image docker.io/bitnami/postgresql:11.11.0-debian-10-r31 --env="PGPASSWORD=$POSTGRES_PASSWORD" --command -- psql --host postgresql-test -U postgres -d postgres -p 5432`

RESULT
![](https://lh5.googleusercontent.com/CNFNeeT9xpoG8GBehHUqa8RI6DtlQiLhzdu7IECib84bnhm26D9wg012EDl3rqm7E1jKHN6_JHRkO2qkggYYuDlfRh-le36HW9ySv5jTmzk0sjy-9kjgineZy09XJM6AHXWKt1Y)

After connecting to the database successfully, we can verify our installation by checking the server version.

### Configuration Options

Depending on the selected helm chart, the available configuration options may differ. The bitnami PostgreSQL chart offers a whole host of options from simple user creation to complex security configurations like setting up certificates and policies. All the available options are listed on the helm chart [GitHub page](https://github.com/bitnami/charts/tree/master/bitnami/postgresql).

Let's look at some common options, such as changing the username, password, database name, and port. This can be done by providing the following parameters while installing the helm chart.
```
helm install postgresql-test01 bitnami/postgresql --set
global.postgresql.postgresqlUsername=testadmin --set
global.postgresql.postgresqlPassword=testadmin123 --set
global.postgresql.postgresqlDatabase=testdb --set
global.postgresql.servicePort=5555
```
RESULT
![](https://lh3.googleusercontent.com/erZ-DCwhb_z25GDueUNnCvfnErsGmcUl4ZGmxEtE4UJr60wNbw8l6n4TTNrQ0Zx0MrcmLE2rdUUqDDMFD-7AJhnY9bfpIfA_mLL_7z5kTTNkL8G2IfbRt86cRQuxDbLppXzOJfM)

The above output indicates that the new port is configured, and a new user is created. If we export the password for the “testadmin” user, it will return the user-defined password.

`export POSTGRES_PASSWORD=$(kubectl get secret --namespace default postgresql-test01 -o jsonpath="{.data.postgresql-password}" | base64 --decode)`

RESULT
![](https://lh6.googleusercontent.com/BH_afvPu7DCofbL7knn0TAO2_HzFx9qom27ZappPU9VjVtwX7bf7OvGwXUHCNYElTlwEmEU7DbG5Jm4oFrsGeLFM9vMl49h2K51COXrD1hiFl7G0H45wla52d6LEm5lRXtmAGPU)

Another common scenario is to configure persistent storage for PostgreSQL deployment. We need to create persistent storage volume before installing the helm chart. The below code block shows how to create a simple storage volume and a volume claim and then attach it to the PostgreSQL deployment.

test-pv.yaml
```
apiVersion: v1
kind: PersistentVolume
metadata:
  name: postgresql-pv
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/mnt/data"
```
  
test-pvc.yaml
```
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: postgresql-pv-claim
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
```
  
Create the volume and claim
`kubectl apply -f test-pv.yaml`
`kubectl apply -f test-pvc.yaml`  
`kubectl get pvc`

RESULT
![](https://lh6.googleusercontent.com/ZCXODiK24_si0ndYEkaZybmDNdnzXMT-v6O-sPUrBAhRxBxNid9YYcatD772jMRmS9Xnn9kXnItiNTRWHXW9zml8w2rk-J_Cimh_b0-6ZIkynu2-3lTrxl0DtJENjv1nuaS7cF0)

Then, we can attach the persistent volume claim to the helm chart using the following command. We will set the “volumePermissions.enabled” to true for mitigating any permission issues that can occur when writing to the storage volume.
```
helm install postgresql-test02 bitnami/postgresql --set
persistence.existingClaim=postgresql-pv-claim --set
volumePermissions.enabled=true
```
  
RESULT
![](https://lh3.googleusercontent.com/edGbrqBjCGxKhI_AQlVTsWSVUY2k_4cwnTDLPiclKl91-HyqB3uBmcHCgBFJSrgb1zhRhzicYf_-UhIVO38bZZPfxw7uKCZHASPukM03USbMCyPFtXJFWcVt220C7Me0yiqmvZQ)

## Upgrading Helm Chart
When upgrading the PostgreSQL helm, it is essential to provide the existing postgresqlPassword and replication.password parameters. It will ensure these values are not updated with random details, which will lead to an inaccessible database.

Syntax
```
helm upgrade <Pod Name>  <Chart Name> --set
postgresqlPassword=<POSTGRESQL_PASSWORD> --set
replication.password=<REPLICATION_PASSWORD>
```

Code
```
helm upgrade postgresql-test bitnami/postgresql --set
postgresqlPassword=testadmin123 --set
replication.password=12345
```
 
RESULT
![](https://lh4.googleusercontent.com/KsjTgWis7XuQ57qEbJ4usyFEjawDwZpe2wnF8rcCpl3YWOPiF8C4lSaGZAGvMcgpDvMribZUI-fmKT3-Sehl4jyLEHCbclLHmPrP9ChZS9wdnk3quPOhRuxsrF6AqXLMOKNoJuQ)

## Deleting a Helm Chart

We can simply delete a helm chart by providing the chart name with the delete command, as shown below.

Syntax
`helm delete <Chart Name>`

Code
`helm delete postgresql-test`

RESULT
![](https://lh4.googleusercontent.com/bsEDYTprWP2MEqKWm209x2g1w4D1ESt9-Mkp_CVfKwUOZz1mIiKdDQCdgid90aiZVOW7W5TzHb98xneVFPN7GW_VZNIK63sb6cs6Y9GT40cAJt4eJKclHCDSgGVWZkPbkowdWRw)

However, this would not delete any PVC associated with the chart. So we need to delete the unused PVCs manually.
`kubectl get pvc`  
`kubectl delete pvc data-postgresql-test-postgresql-0`

RESULT
![](https://lh5.googleusercontent.com/muuEfjaa2e1ngJf2kBgY6L-7PAlQ--D4904lMu4YHU_3xcLFt3QFTOqsCDJ7685j93LoGZSetwyfZK95-TT6Lx76uKWNrKHHOu59A5DIM9E8XeW5DcRlcZD4t9p7D0WpRDWSX80)

## Conclusion
In this article, we learned how to deploy a PostgreSQL database in a Kubernetes cluster using a helm chart, change the configurations, and upgrade and delete the PostgreSQL chart. Using helm charts is a relatively straightforward method to deploy commonly used applications in a Kubernetes cluster. This frees up the users to concentrate on the development of the database without having to create complex Kubernetes configurations.