在Kubernetes上部署有状态应用程序(数据库):
步骤1:部署MySQL服务
apiVersion: v1 kind: Service metadata: name: mysql spec: ports: - port: 3306 selector: app: mysql clusterIP: None
首先,我们在端口3306上为MySQL数据库部署服务,所有Pod均具有标签键app: mysql。
接下来,创建以下资源:Kubectl create -f mysql_service.yaml
步骤2:部署MySQL Deployment
apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2 kind: Deployment metadata: name: mysql spec: selector: matchLabels: app: mysql strategy: type: Recreate template: metadata: labels: app: mysql spec: containers: - image: mysql:5.6 name: mysql env: # Use secret in real usage - name: MYSQL_ROOT_PASSWORD value: password ports: - containerPort: 3306 name: mysql volumeMounts: - name: mysql-persistent-storage mountPath: /var/lib/mysql volumes: - name: mysql-persistent-storage persistentVolumeClaim: claimName: mysql-pv-claim
此Deployment在3306端口上创建带有MySQL5.6镜像和密码(使用secret)的Pod。我们还将附加一个持久卷mysql-pv-claim,将在接下来的步骤中进行显示。
创建资源:Kubectl create -f mysql_deployment.yaml
第3步:创建持久卷
apiVersion: v1 kind: PersistentVolume metadata: name: mysql-pv-volume labels: type: local spec: # persistentVolumeReclaimPolicy: Retain storageClassName: manual capacity: storage: 20Gi accessModes: - ReadWriteOnce hostPath: path: "/mnt/data"
这将创建一个持久卷,我们将使用它来附加到容器,以确保Pod重启时的数据安全。该持久卷具有ReadWriteOne访问模式,拥有20GB的存储空间,存放路径是 ” /mnt/data
“,我们所有的数据都将保存在该路径中。
创建以下资源:Kubectl create -f persistence_volume.yaml
第4步:创建持久卷声明
apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mysql-pv-claim spec: storageClassName: manual accessModes: - ReadWriteOnce resources: requests: storage: 20Gi
该声明从上面创建的“持久卷”中声明20GB,并具有与上面的“持久卷”相同的访问模式。
创建以下资源:Kubectl create -f pvClaim.yaml
完整yaml文件,包含Service, Deployment, PersistentVolume, PersistentVolumeClaim:
apiVersion: v1 kind: Service metadata: name: mysql spec: ports: - port: 3306 selector: app: mysql clusterIP: None --- apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2 kind: Deployment metadata: name: mysql spec: replicas: 1 selector: matchLabels: app: mysql strategy: type: Recreate template: metadata: labels: app: mysql spec: containers: - image: mysql:5.6 name: mysql env: # Use secret in real usage - name: MYSQL_ROOT_PASSWORD value: password ports: - containerPort: 3306 name: mysql volumeMounts: - name: mysql-persistent-storage mountPath: /var/lib/mysql volumes: - name: mysql-persistent-storage persistentVolumeClaim: claimName: mysql-pv-claim --- apiVersion: v1 kind: PersistentVolume metadata: name: mysql-pv-volume labels: type: local spec: # persistentVolumeReclaimPolicy: Retain storageClassName: manual capacity: storage: 1Gi accessModes: - ReadWriteOnce hostPath: path: "/mnt/data" --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mysql-pv-claim spec: storageClassName: manual accessModes: - ReadWriteOnce resources: requests: storage: 1Gi
运行:kubectl apply -f mysql.yaml
步骤5:测试MySQL数据库
kubectl exec -it [pod-name] -- mysql -h mysql -ppassword
此命令在运行MySQL的集群中连接到一个Pod,并连接到MySQL服务器。如果连接成功,则说明你的MySQL数据库已启动并正在运行。
参考: