 # Deployment to manage Postgres instance pods for user service
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: user
  name: user-db
spec:
  replicas: 1
  selector:
    matchLabels:
      app: user
      kind: db
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: user
        kind: db
      name: user-db
    spec:
      hostname: user-db
      containers:
      - env:
        - name: PGUSER
          value: postgres
        image: postgres:12.1
        name: user-db
        volumeMounts:
          # Mount the PV claim from the storage file
        - mountPath: /var/lib/postgresql/data
          name: user-db-claim
          # Mount the SQL script from Config Map
        - mountPath: /docker-entrypoint-initdb.d/init.sql
          # subPath allows mounting a single file, not a directory
          subPath: init.sql
          name: user-db-init
        lifecycle:
          postStart:
            exec:
              # This pod can occasionally fail to start the first time, but still creates files
              # This causes the init db step to be skipped, so this command manually re-runs it
              command: ["/bin/sh", "-c", "psql -U postgres -f /docker-entrypoint-initdb.d/init.sql && echo done"]
      restartPolicy: Always
      volumes:
      - name: user-db-init
        configMap:
          name: user-db-config
      - name: user-db-claim
        persistentVolumeClaim:
          claimName: user-db-claim
