1. 创建一个对外可使用的数据库, 外部网络访问使用NodePort. pod使用到PV,PVC, Secret.

2. 使用PV和PVC创建硬盘, PersistentVolume持久卷, 持久卷申请.

  1. 创建持久卷 pv-maria.yaml, 这里在node节点上申请hostPath申请空间
apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-hostpath
spec:
  capacity:
    storage: 300Mi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/root/mariadb"

  1. 创建持久卷申请pvc-maria.yaml, 申请容量与PV一致才会绑定成功.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pvc-hostpath
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: ""
  resources:
    requests:
      storage: 200Mi

3. 为数据库root密码创建Secret文件mariapass.yml. root密码需要base64转换.

apiVersion: v1
kind: Secret
metadata:
  name: mariapass
type: Opaque
data:
  password: <base64加密你的root密码>
  username: cm9vdA==

4. 创建数据库pod, 使用mariapass.yml中密码和PVC. 创建文件mariadb.yaml

在env中使用密码, 在volumes使用PVC

apiVersion: v1
kind: Service
metadata:
  name: mysql
spec:
  type: NodePort
  ports:
  - port: 3306
    targetPort: 3306
    nodePort: 30016
  selector:
    app: mysql
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: mysql
spec:
  selector:
    matchLabels:
      app: mysql
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
      - name: mysql
        image: mariadb:10.2
        env:
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mariapass
              key: password
        ports:
        - name: mysql
          containerPort: 3306
        volumeMounts:
        - name: mysql-persistent-storage
          mountPath: /var/lib/mysql
      volumes:
      - name: mysql-persistent-storage
        persistentVolumeClaim:
          claimName: pvc-hostpath

5. 设置网络接收规则, 解决nodepod模式外网无法访问mysql服务问题

iptables -P FORWARD ACCEPT

firewall-cmd --zone=public --add-port=30015/tcp --permanent

firewall-cmd --reload

systemctl stop firewalld

开始创建

kubectl apply -f mariadb.yaml,mariapass.yml,pv-maria.yaml,pvc-maria.yaml

# 查看创建的pv pvc pod

kubectl get pv

kubectl get pvc

kubectl get pods

测试连接

mysql -uroot -h<你的IP> -P30016 -p