创建本地目录用于mysql持久化

创建持久化文件mkdir -p /Users/renzhengxin/IdeaProjects/k8s/mysql/v56/data

创建持久卷

创建持久卷定义vim mysql-pv.yaml

apiVersion: v1
kind: PersistentVolume
metadata:
  name: mysal56-pv
  labels:
    pv: mysql56-pv
spec:
  capacity:
    storage: 20Gi
  accessModes:
  - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  hostPath:
    #此处可自定义本地已存在的路径
    path: /Users/renzhengxin/IdeaProjects/k8s/mysql/v56/data

执行创建持久卷:kubectl create -f mysql-pv.yaml
查看持久卷:kubectl get pv
查询持久卷结果

创建持久卷声明

创建持久卷声明定义vim mysql-pvc.yaml

kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: mysql56-pvc
spec:
  # 必须声明下面此行,否则会自动创建pv而不是绑定到已有pv
  storageClassName: ""
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  selector:
    matchLabels:
      pv: mysql56-pv

执行创建持久卷声明:kubectl create -f mysql-pvc.yaml
查看持久卷声明:kubectl get pvc
查看持久卷:kubectl get pv
查看持久卷和持久卷声明结果

创建Deployment

创建Deployment定义vim mysql-deploy.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql56-deploy
spec:
  replicas: 1
  selector:
    matchLabels:
      name: mysql56-ops
  template:
    metadata:
      labels:
        name: mysql56-ops
    spec:
      containers:
        - name: mysql56
          # 此处为M1版本的macOS使用的镜像,一般非arm架构的mac/linux使用mysql:5.6即可
          image: amd64/mysql:5.6
          imagePullPolicy: IfNotPresent
          env:
          # 设置mysql的密码
          - name: MYSQL_ROOT_PASSWORD
            value: "mysql56"
          ports:
            - containerPort: 3306
          volumeMounts:
            - name: mysql-persistent-storage
              mountPath: "/var/lib/mysql"
      volumes:
        - name: mysql-persistent-storage
          persistentVolumeClaim:
            claimName: mysql56-pvc

执行创建Deployment:kubectl create -f mysql-deploy.yaml
查看Deployment:kubectl get deploy
查看Pod:kubectl get po
测试转发到本地端口并连接:kubectl port-forward deploy/mysql56-deploy 30056:3306
查看Deploy和Pod结果
本地mysql-client连接k8s中安装的mysql-server结果

创建服务

创建服务定义vim mysql-svc.yaml

apiVersion: v1
kind: Service
metadata:
  name: mysql56-svc
  labels:
    name: mysql56-svc
spec:
  type: NodePort
  ports:
  - port: 3306
    protocol: TCP
    targetPort: 3306
    name: http
    # nodePort的端口号必须大于30000
    nodePort: 30056
  selector:
    name: mysql56-ops

执行创建服务:kubectl create -f mysql-svc.yaml
查看服务:kubectl get svc
创建服务结果

本地mysql-client连接:
本地mysql-client连接结果

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐