在k8s上使用本地存储运行一个有状态的应用程序(MySQL)

2018-05-29 2939点热度 0人点赞 0条评论

参考文章

Run a Single-Instance Stateful Application

创建k8s本地存储类、持久化存储卷、持久化存储卷声明

创建本地存储类

storage_class.yaml文件内容如下:

kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: local-storage
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer

持久化存储卷

localpv.yaml

apiVersion: v1  
kind: PersistentVolume  
metadata:  
 name: k8s-pv  
 annotations:  
       "volume.alpha.kubernetes.io/node-affinity": '{  
           "requiredDuringSchedulingIgnoredDuringExecution": {  
                "nodeSelectorTerms":[  
                    {"matchExpressions": [  
                        { "key":"kubernetes.io/hostname",  
                          "operator":"In",  
                          "values":["k8s-m1"]  
                        }  
                    ]}  
                 ]}  
              }'  
spec:  
   capacity:  
     storage: 100Gi  
   accessModes:
    - ReadWriteOnce
   persistentVolumeReclaimPolicy: Delete  
   storageClassName: local-storage  
   local:  
     path: /home/wangxianfeng/k8s/data

持久化存储卷声明

mysql-pvc.yaml

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-pv-claim
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 20Gi
  storageClassName: local-storage

mysql deloyment

mysql_deployment.yaml

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: k8s-pv
          mountPath: /var/lib/mysql
      volumes:
      - name: k8s-pv
        persistentVolumeClaim:
          claimName: mysql-pv-claim

mysql service

mysql_service.yaml

apiVersion: v1
kind: Service
metadata:
  name: mysql
spec:
  ports:
  - port: 3306
  selector:
    app: mysql
  clusterIP: None

访问此数据库

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

输入之后进入命令行,输入一个命令试试:

[wangxianfeng@k8s-m1 k8s]$ kubectl run -it --rm --image=mysql:5.6 --restart=Never mysql-client -- mysql -h mysql -ppassword
If you don't see a command prompt, try pressing enter.
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

删除命令

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

王显锋

激情工作,快乐生活!

文章评论