PostgreSQL is a powerful database and we can scale it easy with Kubernetes
In this case we gonna use Kubernetes to store our pods of Postgres with a data value external because if we any pod stop accidentally we won’t lose our data.
Configuring our Storageclass
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
namespace: kube-system
name: standard
annotations:
storageclass.kubernetes.io/is-default-class: "true"
labels:
addonmanager.kubernetes.io/mode: EnsureExists
provisioner: k8s.io/minikube-hostpath
Now we gonna configure our Persistent Volume with 5GB to store our data locally (path var/data), enabling just one pod access it par time.
kind: PersistentVolume
apiVersion: v1
metadata:
name: postgres-pv
labels:
app: postgres
type: local
spec:
storageClassName: standard
capacity:
storage: 5Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/var/data"
----
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: postgres-pv-claim
labels:
app: postgres
spec:
storageClassName: standard
capacity:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5Gi
Let’s configure our Configmap with the data to access our DB
apiVersion: v1
kind: ConfigMap
metadata:
name: postgres-configuration
labels:
app: postgres
data:
POSTGRES_DB: awesomedb
POSTGRES_USER: amazinguser
POSTGRES_PASSWORD: perfectpassword
Now let’s order 3 instances of our DB PostgreSQL 13
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres-statefulset
labels:
app: postgres
spec:
serviceName: "postgres"
replicas: 3
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:13
envFrom:
- configMapRef:
name: postgres-configuration
ports:
- containerPort: 5432
name: postgresdb
volumeMounts:
- name: pv-data
mountPath: /var/lib/postgresql/data
volumes:
- name: pv-data
persistentVolumeClaim:
claimName: postgres-pv-claim
Finally let’s create a service to enable our DB be accessible
apiVersion: v1
kind: Service
metadata:
name: postgres-service
labels:
app: postgres
spec:
ports:
- port: 5432
name: postgres
type: NodePort
selector:
app: postgres
Good! now we already have our yaml ready to be installed! so let’s do it!
kubectl apply -f k8s_postgres_13.yaml
If everything is good we can check our BD running:
kubectl get pods
Voila! our PostgreSQL is installed and running on Kubernetes! let’s test it!
kubectl port-forward postgres-service 5432:5432
Good! you can use your client preferred to use your PostgreSQL!
The file YAML complete: https://github.com/rondweb/kubernetes/blob/main/postgres/k8s_postgres_13.yaml