跳到主要内容

部署有状态应用

部署一个 mysql 实例

注意:密码这里直接写配置里是不安全的

定义部署文件

apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
ports:
- port: 3306
selector:
app: mysql
clusterIP: None
---
apiVersion: apps/v1
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

定义持久化存储和声明

apiVersion: v1
kind: PersistentVolume
metadata:
name: mysql-pv-volume
labels:
type: local
spec:
storageClassName: manual
capacity:
storage: 20Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/mnt/data"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mysql-pv-claim
spec:
storageClassName: manual
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 20Gi

部署 pv 和 pvc 配置

kubectl apply -f https://k8s.io/examples/application/mysql/mysql-pv.yaml

部署 mysql 服务

kubectl apply -f https://k8s.io/examples/application/mysql/mysql-deployment.yaml

查看 mysql 服务

kubectl describe deployment mysql

查看 pods

kubectl get pods -l app=mysql

查看 pvc

kubectl describe pvc mysql-pv-claim

访问 mysql 服务

部署的配置项 clusterIP: None 让服务的 DNS 名称可以直接解析到 pod 的 ip 上。这是服务只有一个 pod,并且后期不会增加的情况下最理想的选择。

kubectl run -it --rm --image=mysql:5.6 --restart=Never mysql-client -- mysql -h mysql -ppassword

更新

  • 不能扩展应用,以上操作只适用于单实例应用,pv 只能挂在到 一个 pod。
  • strategy: type: Recreate 指定不能滚动更新,更新的时候,会先停止原来的 pod,再创建新的 pod。

删除部署

kubectl delete deployment,svc mysql
kubectl delete pvc mysql-pv-claim
kubectl delete pv mysql-pv-volume

If you manually provisioned a PersistentVolume, you also need to manually delete it, as well as release the underlying resource. If you used a dynamic provisioner, it automatically deletes the PersistentVolume when it sees that you deleted the PersistentVolumeClaim. Some dynamic provisioners (such as those for EBS and PD) also release the underlying resource upon deleting the PersistentVolume.

参考