K8s部署单机Mysql

作草分茶About 1 min

K8s部署单机Mysql

配置密码

  1. 给 mysql 配置密码,用到 k8s Secret,需要用 base64 编码。
$ echo 'mysql_pass' | base64
bXlzcWxfcGFzcwo=
  1. 编写配置文件mysql-secret.yml并应用kubectl apply -f mysql-secret.yml
apiVersion: v1
kind: Secret
metadata:
  name: mysql-secret
type: Opaque
data:
  password: bXlzcWxfcGFzcwo=

声明 PV 和 PVC

新建 PV 和 PVC 配置文件mysql-pv-pvc.yaml并应用kubectl apply -f mysql-pv-pvc.yaml

部署 mysql deployment

创建配置文件mysql-deploy.yml并应用kubectl apply -f mysql-deploy.yml

以下提供 Host 和 NFS 两种方式的配置(NSF需要自己搭建服务)。

apiVersion: apps/v1
kind: Deployment
metadata:
  name:  mysql
  namespace: default
  labels:
    app:  mysql
spec:
  selector:
    matchLabels:
      app: mysql
  replicas: 1
  template:
    metadata:
      labels:
        app:  mysql
    spec:
      containers:
      - name:  mysql
        image:  mysql:8
        resources:
          requests:
            cpu: 500m
            memory: 500Mi
          limits:
            cpu: 500m
            memory: 500Mi
        env:
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql-secret
              key: password
        ports:
        - containerPort: 3306
          name:  mysql
        volumeMounts:
        - name: mysql-data
          mountPath: /var/lib/mysql
      volumes:
        - name: mysql-data
          persistentVolumeClaim:
            claimName: mysql-pvc
      restartPolicy: Always

定义 service 提供服务

常见 service 配置文件mysql-service.yml并应用kubectl apply -f mysql-service.yml

apiVersion: v1
kind: Service
metadata:
  labels:
    app: mysql-svc
  name: mysql-svc
spec:
  selector:
    app: mysql
  type: NodePort
  ports:
  - port: 3306
    protocol: TCP
    targetPort: 3306
    nodePort: 30306

验证网络有没有问题

$ telnet 127.0.0.1 30306
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
J
8.0.27z]:PJ
�%,p{nn&_caching_sha2_password