- 密码文件:MySQL Secret
mkdir -p /opt/mysql
mkdir -p /data/mysql
cat > /opt/mysql/mysql-secret.yaml << EOF
apiVersion: v1
kind: Secret
metadata:name: mysql-secret
type: Opaque
data:mysql-root-password: cGFzc0AxMjM0mysql-database: VGVzdA==mysql-user: ZGJyZWFkZXI=mysql-password: ZGJyZWFkZXI=
EOFkubectl apply -f /opt/mysql/mysql-secret.yaml
- 持久化存储:PersistentVolume、PersistentVolumeClaim
cat > /opt/mysql/mysql-pv.yaml << EOF
apiVersion: v1
kind: PersistentVolume
metadata:name: mysql-pv
spec:capacity:storage: 10GiaccessModes:- ReadWriteOncehostPath:path: /data/mysql
EOF
kubectl apply -f /opt/mysql/mysql-pv.yamlcat > /opt/mysql/mysql-pvc.yaml << EOF
apiVersion: v1
kind: PersistentVolumeClaim
metadata:name: mysql-pvc
spec:accessModes:- ReadWriteOnceresources:requests:storage: 10Gi
EOF
kubectl apply -f /opt/mysql/mysql-pvc.yaml
- 配置文件:MySQL Deployment
cat > /opt/mysql/mysql-deployment.yaml << EOF
apiVersion: apps/v1
kind: Deployment
metadata:name: mysql-deployment
spec:replicas: 1selector:matchLabels:app: mysqltemplate:metadata:labels:app: mysqlspec:containers:- name: mysqlimage: mysql:latestenv: - name: MYSQL_ROOT_PASSWORDvalueFrom:secretKeyRef:name: mysql-secretkey: mysql-root-password- name: MYSQL_DATABASEvalueFrom:secretKeyRef:name: mysql-secretkey: mysql-database- name: MYSQL_PASSWORDvalueFrom:secretKeyRef:name: mysql-secretkey: mysql-passwordports:- containerPort: 3306volumeMounts:- name: mysql-storagemountPath: /var/lib/mysqlvolumes:- name: mysql-storagepersistentVolumeClaim:claimName: mysql-pvc
---
apiVersion: v1
kind: Service
metadata:name: mysql-service
spec:type: NodePortports:- port: 3306targetPort: 3306nodePort: 30006selector:app: mysql
EOFkubectl apply -f /opt/mysql/mysql-deployment.yaml
- 利用cronjob实现备份
mkdir -p /backup/mysql
cat > /opt/mysql/mysql-backup-cronjob.yaml << EOF
apiVersion: batch/v1
kind: CronJob
metadata:name: mysql-backup
spec:schedule: "0 3 * * *" # 可以根据需要调整备份时间jobTemplate:spec:template:spec:containers:- name: mysql-backupimage: mysql:latest # 确保这个镜像中包含 mysqldumpcommand:- /bin/sh- -c- |mysqldump -h mysql-service -uroot -p$MYSQL_ROOT_PASSWORD $MYSQL_DATABASE > /backup/mysql/backup-$(date +\%F-\%H\%M\%S).sqlenv:- name: MYSQL_ROOT_PASSWORDvalueFrom:secretKeyRef:name: mysql-secretkey: mysql-root-password- name: MYSQL_DATABASEvalueFrom:secretKeyRef:name: mysql-secretkey: mysql-databasevolumeMounts:- name: backup-storagemountPath: /backup/mysqlvolumes:- name: backup-storagepersistentVolumeClaim:claimName: mysql-pvcrestartPolicy: OnFailure
EOF
kubectl apply -f /opt/mysql/mysql-backup-cronjob.yaml
- 查看状态
kubectl get pods
#NAME READY STATUS RESTARTS AGE
#mysql-deployment-57b4b9987c-h458p 1/1 Running 2 (15m ago) 15m