How to Deploy PostgreSQL on Kubernetes

Introduction

PostgreSQL is a reliable and robust relational database system featuring ACID-compliant transactions. It is designed to handle workloads of all sizes, making it a good fit for personal use and large-scale deployments such as data warehouses, big data servers, or web services.

Deploying PostgreSQL on Kubernetes creates a scalable and portable PostgreSQL instance, leveraging the good sides of both the RDBMS and the orchestration platform.

This article will show you two methods of deploying PostgreSQL on Kubernetes - using a Helm chart or manually creating your configuration.

How to Deploy PostgreSQL on Kubernetes

Prerequisites

Deploy PostgreSQL Using Helm

Helm gives you a quick and easy way to deploy a PostgreSQL instance on your cluster.

Step 1: Add Helm Repository

1. Search Artifact Hub for a PostgreSQL Helm chart that you want to use. Add the chart's repository to your local Helm installation by typing:

helm repo add [repository-name] [repository-address]

This article uses the Bitnami Helm chart for PostgreSQL installation.

Adding the Bitnami helm repository containing a PostgreSQL chart

2. After you have added the repository, update your local repositories.

helm repo update

The system confirms the successful update.

Updating local Helm repositories

Step 2: Create and Apply Persistent Storage Volume

The data in your Postgres database need to persist across pod restarts.

1. To achieve this, create a PersistentVolume resource in a YAML file, using a text editor such as nano.

nano postgres-pv.yaml

The contents of the file define:

  • The resource itself.
  • The storage class.
  • The amount of allocated storage.
  • The access modes.
  • The mount path on the host system.

This example uses the following configuration:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: postgresql-pv
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/mnt/data"

2. Save the file and exit. Then apply the configuration with kubectl:

kubectl apply -f postgres-pv.yaml

The system confirms the creation of the persistent volume.

Applying persistent storage volume for PostgreSQL before installing PostgreSQL with Helm

Step 3: Create and Apply Persistent Volume Claim

1. Create a Persistent Volume Claim (PVC) to request the storage allocated in the previous step.

nano postgres-pvc.yaml

The example uses the following configuration:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: postgresql-pv-claim
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi

2. Save the file and exit. Apply the configuration with kubectl:

kubectl apply -f postgres-pvc.yaml

The system confirms successful PVC creation.

Applying Persistent Volume Claim for PostgreSQL before installing PostgreSQL with Helm

3. Use kubectl get to check if the PVC is connected to the PV successfully:

kubectl get pvc

The status column shows that the claim is Bound.

Checking if the created persistent volume claim was properly bound

Step 4: Install Helm Chart

Install the helm chart with the helm install command. Add --set flags to the command to connect the installation to the PVC you created and enable volume permissions:

helm install [release-name] [repo-name] --set persistence.existingClaim=[pvc-name] --set volumePermissions.enabled=true

The system displays a report upon successful installation.

Installing PostgreSQL with Helm and setting additional parameters

Step 5: Connect to PostgreSQL Client

1. Export the POSTGRES_PASSWORD environment variable to be able to log into the PostgreSQL instance:

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

2. Open another terminal window and type the following port forwarding command to forward the Postgres port:

kubectl port-forward --namespace default svc/psql-test-postgresql 5432:5432

The system starts handling the port connection.

Forwarding the port 5432 using kubectl

3. Minimize the port-forwarding window and return to the previous one. Type the command to connect to psql, a PostgreSQL client:

PGPASSWORD="$POSTGRES_PASSWORD" psql --host 127.0.0.1 -U postgres -d postgres -p 5432

Note: If you do not have psql, use apt to install it:

sudo apt install postgresql-client-12

The psql command prompt appears, and the PostgreSQL is ready to receive your input.

Connecting to the psql 12 PostgreSQL client

Deploy PostgreSQL by Creating Configuration from Scratch

Manual configuration of Postgres on Kubernetes allows you to fine-tune your deployment configuration.

Step 1: Create and Apply ConfigMap

The ConfigMap resource contains the data that is used during the deployment process.

1. Create a ConfigMap YAML file in a text editor.

nano postgres-configmap.yaml

2. The most important part of the file is the data section, where you provide a name for the database, the username, and the password for logging into the PostgreSQL instance.

The example uses the following parameters in the ConfigMap file.

apiVersion: v1
kind: ConfigMap
metadata:
  name: postgres-config
  labels:
    app: postgres
data:
  POSTGRES_DB: postgresdb
  POSTGRES_USER: admin
  POSTGRES_PASSWORD: test123

3. Save the file and exit. Then apply the resource with kubectl:

kubectl apply -f postgres-configmap.yaml

The system confirms the successful creation of the configuration file.

Applying a PostgreSQL ConfigMap using kubectl

Step 2: Create and Apply Persistent Storage Volume and Persistent Volume Claim

1. Create a YAML file for storage configuration.

nano postgres-storage.yaml

2. The Helm chart deployment method used two separate files for the Persistent Volume and the Persistent Volume Claim, but you can also place both configurations in one file, like in the example below.

kind: PersistentVolume
apiVersion: v1
metadata:
  name: postgres-pv-volume
  labels:
    type: local
    app: postgres
spec:
  storageClassName: manual
  capacity:
    storage: 5Gi
  accessModes:
    - ReadWriteMany
  hostPath:
    path: "/mnt/data"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: postgres-pv-claim
  labels:
    app: postgres
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 5Gi

3. Save the file and exit. Apply the resources with kubectl:

kubectl apply -f postgres-storage.yaml

The system confirms the successful creation of both PV and PVC.

Applying PostgreSQL persistent volume and persistent volume claim using kubectl

4. Check that the PVC is connected to the PV with the following command:

kubectl get pvc

The status of the PVC is Bound, and the PVC is ready to be used in the PostgreSQL deployment.

Checking if the persistent volume claim was successfully bound

Step 3: Create and Apply PostgreSQL Deployment

1. Create a deployment YAML file.

nano postgres-deployment.yaml

2. The deployment file contains configuration of the PostgreSQL deployment and provides specifications for the containers and volumes:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:10.1
          imagePullPolicy: "IfNotPresent"
          ports:
            - containerPort: 5432
          envFrom:
            - configMapRef:
                name: postgres-config
          volumeMounts:
            - mountPath: /var/lib/postgresql/data
              name: postgredb
      volumes:
        - name: postgredb
          persistentVolumeClaim:
            claimName: postgres-pv-claim

3. Save the file and exit. Apply the deployment with kubectl:

kubectl apply -f postgres-deployment.yaml

The system confirms the successful creation of the deployment.

Applying a PostgreSQL deployment using kubectl

Step 4: Create and Apply PostgreSQL Service

1. Lastly, create the YAML file to configure the PostgreSQL service.

nano postgres-service.yaml

2. Specify the service type and ports. The example uses the following configuration:

apiVersion: v1
kind: Service
metadata:
  name: postgres
  labels:
    app: postgres
spec:
  type: NodePort
  ports:
   - port: 5432
  selector:
   app: postgres

3. Save the file and exit. Apply the configuration with kubectl:

kubectl apply -f postgres-service.yaml

The system confirms the successful creation of the service.

Applying a PostgreSQL service using kubectl

4. Use the following command to list all resources on the system.

kubectl get all

The pod and the deployment show the 1/1 ready status. The desired number of replica sets reflect what is configured in the deployment YAML file.

Using kubectl get all to check if all the pods, services, and deployments are ready

Step 5: Connect to PostgreSQL

1. When all the resources are ready, use kubectl exec to log into the PostgreSQL instance.

kubectl exec -it [pod-name] --  psql -h localhost -U admin --password -p [port] postgresdb

2. The system asks for the password. Type in the password defined in Step 1 and press Enter. The psql command prompt appears.

Accessing the psql PostgreSQL client using kubectl exec

The database is now ready to receive user input.

Note: An easy way to deploy a highly available PostgreSQL cluster on bare metal is by using a Rancher-controlled Kubernetes cluster.

Conclusion

After completing this tutorial, you should know how to deploy PostgreSQL on Kubernetes using the manual method and a Helm chart.

For information about working with PostgreSQL databases, read How to Create a Database in PostgreSQL or browse one of the related articles below.

Was this article helpful?
YesNo
Marko Aleksic
Marko Aleksić is a Technical Writer at phoenixNAP. His innate curiosity regarding all things IT, combined with over a decade long background in writing, teaching and working in IT-related fields, led him to technical writing, where he has an opportunity to employ his skills and make technology less daunting to everyone.
Next you should read
How to List All Databases in PostgreSQL
June 9, 2021

One of the important tasks when managing PostgreSQL servers is listing the existing databases and their tables. There are three ways to list all databases...
Read more
PostgreSQL Data Types
July 29, 2021

PostgreSQL is an open-source relational database management system known for its robustness and extensibility. This also means PostgreSQL offers a variety of data types for users.
Read more
How to Install SQL Workbench for PostgreSQL
March 13, 2020

SQL Workbench is a tool designed to handle SQL queries no matter which DBMS you use. This tutorial shows you how to install and set up SQL Workbench for PostgreSQL.
Read more
How to Install PostgreSQL on Windows
June 29, 2021

In this tutorial, we will go over the process of installing PostgreSQL on Windows 10 and show different ways to connect to a PostgreSQL database...
Read more