1. First you have to have a K8S cluster

I have a kubeadm installed on a master/slave k8S cluster []

2. Mysql is stateful, data must be persistent, so pv and PVC are needed

The pv of hostPath is definitely not used in the actual production scenario, because you can’t determine which node the pod is scheduled to. NodeSelector selects this node in the deploy file and mysql will definitely schedule mysql to node01.

pv.yaml

apiVersion: v1
kind: PersistentVolume
metadata:
  name: auth-mysql-pv
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 20Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/home/ubuntu/mysql-volume"
Copy the code

pvc.yaml

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: auth-mysql-pv-claim
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 20Gi
Copy the code

3. Deploy and service

Here the service is exposed through nodePort for testing; Then change to ClusterIP, because once the application is deployed in the cluster, it can only access mysql inside the cluster, and does not need to be exposed outside the cluster

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: auth-mysql
spec:
  replicas: 1
  selector:
    matchLabels:
      app: auth-mysql
  template:
    metadata:
      labels:
        app: auth-mysql
    spec:
      containers:
        - name: mysql
          image: mysql
          imagePullPolicy: IfNotPresent
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: "123456"
          ports:
            - name: mysql
              containerPort: 3306
          volumeMounts:
            - name: mysql-volume
              mountPath: /var/lib/mysql

      volumes:
        - name: mysql-volume
          persistentVolumeClaim:
            claimName: auth-mysql-pv-claim
      nodeSelector:
        app: mysql
Copy the code

Service. Yaml (NodePort)

apiVersion: v1
kind: Service
metadata:
  name: auth-mysql
spec:
  type: NodePort
  ports:
    - port: 3306
      targetPort: 3306
      nodePort: 30306
  selector:
    app: auth-mysql
Copy the code

service.yaml (ClusterIP)

ApiVersion: v1 kind: Service metadata: name: auth-mysql spec: type: ClusterIP # 3306 targetPort: 3306 selector: app: auth-mysqlCopy the code

4 Connection Verification (NodePort, external cluster access)

NodePort creates port 30306, which is connected outside the cluster.

Create database and table:

/var/lib/mysql = /var/lib/mysql = /var/lib/mysql = /var/lib/mysql

Delete pod, automatically pull, find the data is still in, prove persistence success.

5. Change Service to ClusterIP and create a temporary POD to access services from within the cluster

kubectl run -it --rm --image=mysql --restart=Never mysql-client --  mysql -h auth-mysql -p123456
Copy the code