Deploy PostgreSQL on Kubernetes: A Step-by-Step Guide for Beginners

This tutorial describes how to deploy PostgreSQL on Kubernetes

PostgreSQL is a reliable and robust relational database system with ACID-compliant transactions. It’s designed to handle workloads of all sizes, making it ideal 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 instance of PostgreSQL that leverages the benefits of an RDBMS and orchestration platform.

How do I deploy PostgreSQL on Kubernetes?This article will show you two ways to deploy PostgreSQL on Kubernetes – using Helm charts or manually creating configurations.

Prerequisite

  • A Kubernetes cluster with kubectl installed
  • Helm 3 installed
  • Administrative privileges on the system

Use Helm to deploy PostgreSQL

How does Kubernetes deploy PostgreSQL?Helm provides you with a quick and easy way to deploy PostgreSQL instances on your cluster.

Step 1: Add a Helm repository

1. Search for the PostgreSQL Helm chart you want to use in Artifact Hub. Add the repository of the chart to your local Helm installation by typing the following:

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

This article uses the Bitnami Helm chart for PostgreSQL installation.

2. After adding the repository, update the local repository.

helm repo update

The system confirms that the update was successful.

Step 2: Create and apply persistent storage volumes

How do I deploy PostgreSQL on Kubernetes?The data in the Postgres database needs to remain intact after the pod is restarted.

1. To do this, use a text editor (e.g. nano) to create a PersistentVolume resource in a YAML file.

nano postgres-pv.yaml

File Content Definition:

  • The resource itself.
  • Storage classes.
  • The amount of storage allocated.
  • Access mode.
  • The mount path on the host system.

In this example, the following configuration is used:

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 kubectl:

kubectl apply -f postgres-pv.yaml

The system confirms the creation of the persistent volume.

Step 3: Create and apply a persistent volume claim

1. Kubernetes Deployment PostgreSQL Tutorial: Create a Persistent Volume Declaration (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 kubectl:

kubectl apply -f postgres-pvc.yaml

The system acknowledges that the PVC was successfully created.

3.kubectl get is used to check whether the PVC is connected to the PV successfully:

kubectl get pvc

The Status column shows that the declaration is Bound.

Step 4: Install the Helm Chart

Use the helm install command to install the helm chart. --set to add a flag to the command to connect the install to the PVC you created and enable volume permissions:

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

After the installation is successful, the system displays a report.

Step 5: Connect to the PostgreSQL client

1. How do I deploy PostgreSQL on Kubernetes? Export POSTGRES_PASSWORD environment variables to log in to 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 enter the following command to forward the Postgres port:

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

The system starts processing the port connection.

3. Minimize the port forwarding window and go back to the previous one. Enter 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 don’t have psql, install with apt:sudo apt Installation postgresql-client-12

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

Deploy PostgreSQL by creating a configuration from scratch

KubernetesHow does PostgreSQL be deployed?Manually configuring Postgres on Kubernetes allows you to fine-tune your deployment configuration.

Step 1: Create and apply a ConfigMap

The ConfigMap resource contains a piece of data that was 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 can provide the database nameuser name, and password to log in to your 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 kubectl:

kubectl apply -f postgres-configmap.yaml

The system confirms that the configuration file is created.

Step 2: Create and apply persistent storage volumes and persistent volume declarations

1. How does Kubernetes deploy PostgreSQL? Create a YAML file for the storage configuration.

nano postgres-storage.yaml

2. The Helm chart deployment method uses two separate files for Persistent Volume and Persistent Volume Claim, but you can also put the two configurations in one file, as shown 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. Application resource kubectl:

kubectl apply -f postgres-storage.yaml

The system confirms that the PV and PVC were successfully created.

4. Use the following command to check if the PVC is connected to the PV:

kubectl get pvc

The status of the PVC is Bound, and the PVC is ready for PostgreSQL deployment.

Step 3: Create and apply a PostgreSQL deployment

1. Kubernetes Deployment PostgreSQL Tutorial: Create a deployment YAML file.

nano postgres-deployment.yaml

2. The deployment file contains the configuration of the PostgreSQL deployment and provides specifications for 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. Application deployment kubectl:

kubectl apply -f postgres-deployment.yaml

The system confirms that the deployment is created.

Step 4: Create and apply the PostgreSQL service

1. How does Kubernetes deploy PostgreSQL? Finally, create a YAML file to configure the PostgreSQL service.

nano postgres-service.yaml

2. Specify the service type and port. 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 kubectl:

kubectl apply -f postgres-service.yaml

The system confirms that the service is created.

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

kubectl get all

Pods and deployments show a 1/1 readiness status. The number of replica sets required reflects the configuration in the deployment YAML file.

Step 5: Connect to PostgreSQL

1. How do I deploy PostgreSQL on Kubernetes? When all resources are ready, use kubectl exec to log in to the PostgreSQL instance.

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

2. You will be asked to enter your password. Enter the password defined in step 1 and press Enter. The psql command prompts.

The database is now ready to receive user input.

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

Summary of the Kubernetes PostgreSQL Deployment Tutorial

By the end of this tutorial, you should know how to deploy PostgreSQL on Kubernetes using manual methods and Helm charts.

For information about using PostgreSQL databases, read how to create a database in PostgreSQL or explore one of the following related articles.