K8S: PostgreSQL with Persistent Storage Volume
ConfigMap for PostgreSQL Configurations
Create file with configuration postgres-configmap.yaml:
apiVersion: v1
kind: ConfigMap
metadata:
name: postgres-config
labels:
app: postgres
data:
POSTGRES_DB: postgresdb
POSTGRES_USER: postgresadmin
POSTGRES_PASSWORD: admin123
Creat ConfigMap:
kubectl create -f postgres-configmap.yaml
# configmap "postgres-config" created
Persistent Storage Volume
Create file with storage information postgres-storage.yaml:
kind: PersistentVolume
apiVersion: v1
metadata:
name: postgres-pv-volume
labels:
type: local
app: postgres
spec:
storageClassName: manual
capacity:
storage: 5Gi # Should be the same as in PersistentVolumeClaim
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 # Should be the same as in PersistentVolume
Creat Storage Volume:
kubectl create -f postgres-storage.yaml
# persistentvolume "postgres-pv-volume" created
# persistentvolumeclaim "postgres-pv-claim" created
PostgreSQL Deployment
postgres-deployment.yaml
Create file with deployment postgres-deployment.yaml:
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:latest # Available https://hub.docker.com/_/postgres
imagePullPolicy: "IfNotPresent"
ports:
- containerPort: 5432
envFrom:
- configMapRef:
name: postgres-config # postgres-configmap.yaml
volumeMounts:
- mountPath: /var/lib/postgresql/data
name: postgredb
volumes:
- name: postgredb
persistentVolumeClaim:
claimName: postgres-pv-claim # postgres-storage.yaml
Deploy:
kubectl create -f postgres-deployment.yaml
# deployment "postgres" created
Expose PostgreSQL
postgres-deployment.yaml
Create service postgres-service.yaml:
apiVersion: v1
kind: Service
metadata:
name: postgres
labels:
app: postgres
spec:
type: NodePort
ports:
- port: 5432
selector:
app: postgres
Create Service:
kubectl create -f postgres-service.yaml
# service "postgres" created