[Kubernetes] PostgreSQL initdb 설정

  • PV 또는 PVC 설정이 되어 있지 않았을 때
  • PV 또는 PVC 실수로 지웠을 때
  • 환경이 동일하고 같은 테이블을 사용하는 db를 재사용할 때

postgresql pod가 생성될 때 최초로 아래와 같은 기본 테이블 세팅 설정

ConfigMap yaml #

 1apiVersion: v1
 2kind: ConfigMap
 3metadata:
 4  name: postgresql-initdb-config
 5data:
 6  init.sql: |
 7    CREATE TABLE IF NOT EXISTS customers (
 8        customer_id bpchar NOT NULL,
 9        company_name character varying(40) NOT NULL,
10        contact_name character varying(30),
11        contact_title character varying(30),
12        address character varying(60),
13        city character varying(15),
14        region character varying(15),
15        postal_code character varying(10),
16        country character varying(15),
17        phone character varying(24),
18        fax character varying(24)
19    );
20
21 INSERT INTO customers VALUES ('Chris', 'company_name', 'contact_name', 'contact_title', 'address', 'city_name', region_name, 'postal_code', 'Korea', 'phone-number', 'fax-number');

PV yaml #

 1apiVersion: v1
 2kind: PersistentVolume
 3metadata:
 4  name: postgresql-claim0
 5  labels:
 6    type: local
 7spec:
 8  storageClassName: manual
 9  capacity:
10    storage: 1Gi
11  accessModes:
12    - ReadWriteOnce
13  hostPath:
14    path: "/Users/docker/postgres/docker-pg-vol/data"

PVC yaml #

 1apiVersion: v1
 2kind: PersistentVolumeClaim
 3metadata:
 4  name: postgresql-claim0
 5  labels:
 6    app: postgresql
 7    tier: database
 8spec:
 9  accessModes:
10    - ReadWriteOnce
11  resources:
12    requests:
13      storage: 100Mi

Deployment yaml #

 1kind: Deployment
 2metadata:
 3  name: postgresql
 4  labels:
 5    app: postgresql
 6    tier: database
 7spec:
 8  selector:
 9    matchLabels:
10      app: postgresql
11  strategy:
12    type: Recreate
13  template:
14    metadata:
15      labels:
16        app: postgresql
17        tier: database
18    spec:
19      containers:
20        - name: postgresql
21          image: postgres:12
22          imagePullPolicy: "IfNotPresent"
23          env:
24            - name: POSTGRES_DB
25              value: db_name
26            - name: POSTGRES_USER
27              value: postgres
28            - name: POSTGRES_PASSWORD
29              value: setting_password
30          ports:
31            - containerPort: 5432
32              name: postgresql
33          volumeMounts:
34            - name: postgresql-claim0
35              mountPath: /var/lib/postgresql/data
36
37            - mountPath: /docker-entrypoint-initdb.d
38              name: postgresql-initdb
39      volumes:
40        - name: postgresql-claim0
41          persistentVolumeClaim:
42            claimName: postgresql-claim0
43
44        - name: postgresql-initdb
45          configMap:
46            name: postgresql-initdb-config
Advertisement