Skip to content

MySQL in Kubernetes

namespace.yaml

yaml
apiVersion: v1
kind: Namespace
metadata:
  name: common

mysql-deployment.yaml

yaml
---
apiVersion: v1
kind: Service
metadata:
  name: mysql
  namespace: common
spec:
  type: ClusterIP
  ports:
  - port: 3306
  selector:
    app: mysql
  clusterIP: None
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-pv-claim
  namespace: common
spec:
  storageClassName: local
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: mysql-pv-volume
  labels:
    type: local
spec:
  storageClassName: local
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/root/kubernetes/common/mysql/mysql_pv_volume" # 此目录要正确填写
---
kind: Secret
apiVersion: v1
metadata:
  name: common-mysql-root-account
  namespace: common
  annotations:
    kubesphere.io/creator: admin
data:
  username: cm9vdA==
  password:  # 在这里配置密码
type: kubernetes.io/basic-auth
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql
  namespace: common
spec:
  selector:
    matchLabels:
      app: mysql
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
      - image: mysql:8.0.29
        name: mysql
        env:
          # 在实际中使用 secret
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: common-mysql-root-account
              key: password
        ports:
        - containerPort: 3306
          name: mysql
          hostPort: 3306
        volumeMounts:
        - name: mysql-persistent-storage
          mountPath: /var/lib/mysql
      volumes:
      - name: mysql-persistent-storage
        persistentVolumeClaim:
          claimName: mysql-pv-claim

mysql-bash.yaml

yaml
apiVersion: v1
kind: Pod
metadata:
  name: mysql-client
spec:
  restartPolicy: Never
  containers:
  - name: mysql-client
    image: mysql:8.0.29
    command: ["/bin/bash"]
    stdin: true
    tty: true
    volumeMounts:
    - name: data
      mountPath: /scripts
  #volumes:
  #- name: data
  #  hostPath:
  #    path: /root/kubernetes/scripts
  #    type: Directory