(作者:陈玓玏)
一、前置条件
- 已部署k8s,服务端版本为1.21.14
二、部署postgresql
- 拉取镜像,docker pull postgres,不指定版本,自动从docker hub拉取最新版本;
- 配置configmap,保存postgresql的用户名、密码等信息,注意密码如果是数字,需要用双引号裹起来;
apiVersion: v1
kind: ConfigMap
metadata:
name: pg-config
labels:
app: postgres
data:
POSTGRES_DB: pgdb
POSTGRES_USER: pgadmin
POSTGRES_PASSWORD: "123456"
创建 Postgres ConfigMap 资源,kubectl apply -f postgresql.yaml;
3. 持久卷声明,创建pv和pvc,用于数据的持久化存储:
kind: PersistentVolume
apiVersion: v1
metadata:
name: pg-pv-volume
labels:
type: local
app: postgres
spec:
storageClassName: manual
capacity:
storage: 5Gi
accessModes:
- ReadWriteMany
hostPath:
path: "/home/postgresql/data"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: pg-pv-claim
labels:
app: postgres
spec:
storageClassName: manual
accessModes:
- ReadWriteMany
resources:
requests:
storage: 5Gi
保存后通过kubectl apply -f创建pv及pvc。
4. 创建deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: pg-deployment
spec:
strategy:
type: Recreate
selector:
matchLabels:
app: postgres
replicas: 1
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:11.5
imagePullPolicy: "IfNotPresent"
ports:
- containerPort: 5432
envFrom:
- configMapRef:
name: pg-config
volumeMounts:
- mountPath: /var/lib/postgresql/data
name: postgredb
volumes:
- name: postgredb
persistentVolumeClaim:
claimName: pg-pv-claim
主要是要注意其中selector的app和metadata中的app名称要一致,另外引入的configmap名称要和前面的configmap一致等等。创建好yaml文件后,通过kubectl创建deployment。replica写1就好,数据库的副本数一般1就够了,避免读写冲突。
pg的版本如果不记得,可以通过docker images |grep postgresql查一下。
5. 创建service,对外暴露服务入口
apiVersion: v1
kind: Service
metadata:
name: pg-service
labels:
app: postgres
spec:
type: NodePort
ports:
- port: 5432
targetPort: 5432
protocol: TCP
selector:
app: postgres
注意targetPort要和deployment暴露出来的一致,否则无法转发到deployment创建的pod。同样,写好yaml之后通过kubectl apply -f创建service。
三、验证部署结果
- 验证部署是否成功
service可以查询到,再尝试下使用pg,首先下载一个pg的客户端:apt -y install postgresql-client-12,下载完成后,登录pg,通过psql -U pgadmin -h 10.43.25.238 -p 5432 pgdb登录pg,数据库名、用户名、密码、端口、ip在前面都可以找到,能够登录即部署成功。登录成功如下:
参考:
- https://hanggi.me/post/kubernetes/k8s-postgresql/
- https://stackoverflow.com/questions/28290488/get-error-you-must-install-at-least-one-postgresql-client-version-package-whe
- https://blog.csdn.net/dujidan/article/details/128862899