(作者:陈玓玏)
一、前置条件
已部署k8s,服务端版本为1.21.14
二、部署mysql
- 拉取镜像;
docker pull mysql
- 将账号密码等信息写到configmap,创建configmap;
apiVersion: v1
kind: ConfigMap
metadata:
name: mysql-config
labels:
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-volume
labels:
type: local
app: mysql
spec:
storageClassName: manual
capacity:
storage: 5Gi
accessModes:
- ReadWriteMany
hostPath:
path: "/home/mysql/data"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: mysql-pv-claim
labels:
app: mysql
spec:
storageClassName: manual
accessModes:
- ReadWriteMany
resources:
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: Recreate
selector:
matchLabels:
app: mysql
replicas: 1
template:
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:8.0.32
imagePullPolicy: "IfNotPresent"
ports:
- containerPort: 3306
envFrom:
- configMapRef:
name: mysql-config
volumeMounts:
- mountPath: /var/lib/mysql
name: mysqldb
volumes:
- name: mysqldb
persistentVolumeClaim:
claimName: mysql-pv-claim
kubectl创建deployment。这一步一开始我mountPath搞错了,然后在k8sdashboard上看pod日志才发现哪里错了,所以验证有问题时要注意排查。
- 创建service
apiVersion: v1
kind: Service
metadata:
name: mysql-service
labels:
app: mysql
spec:
type: NodePort
ports:
- port: 3306
targetPort: 3306
protocol: TCP
selector:
app: mysql
kubectl创建service。
三、验证部署结果
- 安装mysql客户端:
apt install mysql-client-core-8.0
; - 连接mysql:
mysql -u root -h 10.43.236.29 -p
;