(作者:陈玓玏)
一、前置条件
已部署k8s,服务端版本为1.21.14
二、部署mysql
- 拉取镜像;
docker pull mysql
- 将账号密码等信息写到configmap,创建configmap;
apiVersion: v1
kind: ConfigMap
metadata:name: mysql-configlabels:app: mysql
data:MYSQL_ROOT_PASSWORD: "123456"
执行下面的命令来创建configmap。mysql默认都是Root用户,所以只填了个密码。
kubectl apply -f mysql-cm.yaml
- 持久卷声明,创建pv和pvc,用于数据的持久化存储:
kind: PersistentVolume
apiVersion: v1
metadata:name: mysql-pv-volumelabels:type: localapp: mysql
spec:storageClassName: manualcapacity:storage: 5GiaccessModes:- ReadWriteManyhostPath:path: "/home/mysql/data"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:name: mysql-pv-claimlabels:app: mysql
spec:storageClassName: manualaccessModes:- ReadWriteManyresources:requests:storage: 5Gi
执行下面的命令来创建pv及pvc。
kubectl apply -f mysql-pv-pvc.yaml
- 创建deployment
apiVersion: apps/v1
kind: Deployment
metadata:name: mysql-deployment
spec:strategy:type: Recreateselector:matchLabels:app: mysqlreplicas: 1template:metadata:labels:app: mysqlspec:containers:- name: mysqlimage: mysql:8.0.32imagePullPolicy: "IfNotPresent"ports:- containerPort: 3306envFrom:- configMapRef:name: mysql-configvolumeMounts:- mountPath: /var/lib/mysqlname: mysqldbvolumes:- name: mysqldbpersistentVolumeClaim:claimName: mysql-pv-claim
kubectl创建deployment。这一步一开始我mountPath搞错了,然后在k8sdashboard上看pod日志才发现哪里错了,所以验证有问题时要注意排查。
- 创建service
apiVersion: v1
kind: Service
metadata:name: mysql-servicelabels:app: mysql
spec:type: NodePortports:- port: 3306targetPort: 3306protocol: TCPselector:app: mysql
kubectl创建service。
三、验证部署结果
- 安装mysql客户端:
apt install mysql-client-core-8.0
; - 连接mysql:
mysql -u root -h 10.43.236.29 -p
;