- 密码文件:MySQL Secret
# VGVzdA== -> Test
# ZGJyZWFkZXI= -> root
# cGFzc0AxMjM0 -> pass@1234
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: cGFzc0AxMjM0
mysql-database: VGVzdA==
mysql-user: ZGJyZWFkZXI=
mysql-password: ZGJyZWFkZXI=
EOF
kubectl 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: 10Gi
accessModes:
- ReadWriteOnce
hostPath:
path: /data/mysql
EOF
kubectl apply -f /opt/mysql/mysql-pv.yaml
cat > /opt/mysql/mysql-pvc.yaml << EOF
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mysql-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
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: 1
selector:
matchLabels:
app: mysql
template:
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:latest
env:
- name: MYSQL_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mysql-secret
key: mysql-root-password
- name: MYSQL_DATABASE
valueFrom:
secretKeyRef:
name: mysql-secret
key: mysql-database
- name: MYSQL_PASSWORD
valueFrom:
secretKeyRef:
name: mysql-secret
key: mysql-password
ports:
- containerPort: 3306
volumeMounts:
- name: mysql-storage
mountPath: /var/lib/mysql
volumes:
- name: mysql-storage
persistentVolumeClaim:
claimName: mysql-pvc
---
apiVersion: v1
kind: Service
metadata:
name: mysql-service
spec:
type: NodePort
ports:
- port: 3306
targetPort: 3306
nodePort: 30006
selector:
app: mysql
EOF
kubectl 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-backup
image: mysql:latest # 确保这个镜像中包含 mysqldump
command:
- /bin/sh
- -c
- |
mysqldump -h mysql-service -uroot -p$MYSQL_ROOT_PASSWORD $MYSQL_DATABASE > /backup/mysql/backup-$(date +\%F-\%H\%M\%S).sql
env:
- name: MYSQL_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mysql-secret
key: mysql-root-password
- name: MYSQL_DATABASE
valueFrom:
secretKeyRef:
name: mysql-secret
key: mysql-database
volumeMounts:
- name: backup-storage
mountPath: /backup/mysql
volumes:
- name: backup-storage
persistentVolumeClaim:
claimName: mysql-pvc
restartPolicy: 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