在k8s中,Mysql數據庫的持久化是一個很重要的問題。常見的做法是使用PV(Persistent Volume)和PVC(Persistent Volume Claim)來實現。具體步驟如下:
apiVersion: v1 kind: PersistentVolume metadata: name: mysql-pv labels: type: "local" spec: capacity: storage: "1Gi" accessModes: - "ReadWriteOnce" hostPath: path: "/data/mysql" apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mysql-pvc spec: accessModes: - "ReadWriteOnce" resources: requests: storage: "1Gi"
這段代碼定義了一個PV和PVC,其中容量為1GB。對于PV,使用hostPath來定義該卷對應的主機路徑。對于PVC,使用requests來申請該卷的容量。
接下來創建一個MySQL的Deployment,并掛在上述的PVC:
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:5.7 env: - name: MYSQL_ROOT_PASSWORD value: password ports: - containerPort: 3306 volumeMounts: - name: mysql-pvc mountPath: /var/lib/mysql volumes: - name: mysql-pvc persistentVolumeClaim: claimName: mysql-pvc
這段代碼定義了一個MySQL的Deployment,使用了mysql:5.7的鏡像,指定了root密碼是password,暴露了3306端口,并將PVC掛載到容器的/var/lib/mysql路徑下。
最后,使用Service將該Deployment暴露出去:
apiVersion: v1 kind: Service metadata: name: mysql-service spec: selector: app: mysql ports: - port: 3306 targetPort: 3306 type: ClusterIP
這段代碼定義了一個Service,將mysql的3306端口暴露出去。注意,這里type為ClusterIP。
這樣就完成了MySQL的部署和持久化,可以在k8s中愉快地使用MySQL了。