Search code examples
postgresqlkubernetesglusterfs

postgres on k8s with glusterfs as storage


I deploy a postgres database on k8s and glusterfs as volume.But every time I restart my pod all of data losses.Why is that?

apiVersion: apps/v1       
kind: Deployment               
metadata:     
  name: postgres-deployment
  namespace: gitlab
  labels:                                                                  
    app: postgres 
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - name: postgres
        image: postgres:13.1
        ports:
        - containerPort: 5432
        volumeMounts:
        - mountPath: /var/lib/postgresql
          name: postgres
        env:
        - name: POSTGRES_USERNAME
          valueFrom:
            secretKeyRef:
              name: gitlab
              key: postgres_username
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: gitlab
              key: postgres_password
        - name: POSTGRES_DB
          valueFrom:
            secretKeyRef:
              name: gitlab
              key: postgres_db 
      volumes:
      - name: postgres
        glusterfs:
          endpoints: glusterfs-cluster
          path: gv



Solution

  • Define PVC and PV objects. see below for reference.

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

    Then bind the PVC to the pod as shown below

    apiVersion: apps/v1beta1
    kind: Deployment
    metadata:
      name: postgres
    spec:
      template:
        metadata:
          labels:
            app: postgres
        spec:
          containers:
          - name: postgres
            ...
            volumeMounts:
            - mountPath: /var/lib/postgresql/data
              name: postgres-pv-claim
          volumes:
          - name: postgres-pv-claim
            persistentVolumeClaim:
              claimName: postgres-pv-claim