開發與維運

Kubernetes 部署 MySQL 集群

116.jpg
鏡像下載、域名解析、時間同步請點擊 阿里巴巴開源鏡像站

一、配置準備

1. configMap

#application/mysql/mysql-configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: mysql
  labels:
    app: mysql
data:
  master.cnf: |
    # Apply this config only on the master.
    [mysqld]
    log-bin
  slave.cnf: |
    # Apply this config only on slaves.
    [mysqld]
    super-read-only

configMap可以將配置文件和鏡像解耦開。
上面的配置意思是,創建一個master.cnf文件配置內容為:log-bin,即開啟bin-log日誌,供主節點使用。
創建一個slave.cnf文件配置內容為:super-read-only,設為該節點只讀,供備用節點使用。

2. service

# application/mysql/mysql-services.yaml
# Headless service for stable DNS entries of StatefulSet members.
apiVersion: v1
kind: Service
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  ports:
  - name: mysql
    port: 3306
  clusterIP: None
  selector:
    app: mysql
---
# Client service for connecting to any MySQL instance for reads.
# For writes, you must instead connect to the master: mysql-0.mysql.
apiVersion: v1
kind: Service
metadata:
  name: mysql-read
  labels:
    app: mysql
spec:
  ports:
  - name: mysql
    port: 3306
  selector:
    app: mysql

創建一個服務名為mysql的headless類型的service。
創建一個服務名為mysql-read的service

3. StatefulSet

#application/mysql/mysql-statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  selector:
    matchLabels:
      app: mysql
  serviceName: mysql
  replicas: 3
  template:
    metadata:
      labels:
        app: mysql
    spec:
      # 設置初始化容器,進行一些準備工作
      initContainers:
      - name: init-mysql
        image: mysql:5.7
        # 為每個MySQL節點配置service-id
        # 如果節點序號是0,則使用master的配置, 其餘節點使用slave的配置
        command:
        - bash
        - "-c"
        - |
          set -ex
          # Generate mysql server-id from pod ordinal index.
          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
          ordinal=${BASH_REMATCH[1]}
          echo [mysqld] > /mnt/conf.d/server-id.cnf
          # Add an offset to avoid reserved server-id=0 value.
          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
          # Copy appropriate conf.d files from config-map to emptyDir.
          if [[ $ordinal -eq 0 ]]; then
            cp /mnt/config-map/master.cnf /mnt/conf.d/
          else
            cp /mnt/config-map/slave.cnf /mnt/conf.d/
          fi
        volumeMounts:
        - name: conf
          mountPath: /mnt/conf.d
        - name: config-map
          mountPath: /mnt/config-map
      - name: clone-mysql
        image: gcr.io/google-samples/xtrabackup:1.0
        # 為除了節點序號為0的主節點外的其它節點,備份前一個節點的數據
        command:
        - bash
        - "-c"
        - |
          set -ex
          # Skip the clone if data already exists.
          [[ -d /var/lib/mysql/mysql ]] && exit 0
          # Skip the clone on master (ordinal index 0).
          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
          ordinal=${BASH_REMATCH[1]}
          [[ $ordinal -eq 0 ]] && exit 0
          # Clone data from previous peer.
          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
          # Prepare the backup.
          xtrabackup --prepare --target-dir=/var/lib/mysql
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
      containers:
      - name: mysql
        image: mysql:5.7
        # 設置支持免密登錄
        env:
        - name: MYSQL_ALLOW_EMPTY_PASSWORD
          value: "1"
        ports:
        - name: mysql
          containerPort: 3306
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
        resources:
          # 設置啟動pod需要的資源,官方文檔上需要500m cpu,1Gi memory。
          # 我本地測試的時候,會因為資源不足,報1 Insufficient cpu, 1 Insufficient memory錯誤,所以我改小了點
          requests:
            # m是千分之一的意思,100m表示需要0.1個cpu
            cpu: 100m
            # Mi是兆的意思,需要100M 內存
            memory: 100Mi
        livenessProbe:
          # 使用mysqladmin ping命令,對MySQL節點進行探活檢測
          # 在節點部署完30秒後開始,每10秒檢測一次,超時時間為5秒
          exec:
            command: ["mysqladmin", "ping"]
          initialDelaySeconds: 30
          periodSeconds: 10
          timeoutSeconds: 5
        readinessProbe:
          # 對節點服務可用性進行檢測, 啟動5秒後開始,每2秒檢測一次,超時時間1秒
          exec:
            # Check we can execute queries over TCP (skip-networking is off).
            command: ["mysql", "-h", "127.0.0.1", "-e", "SELECT 1"]
          initialDelaySeconds: 5
          periodSeconds: 2
          timeoutSeconds: 1
      - name: xtrabackup
        image: gcr.io/google-samples/xtrabackup:1.0
        ports:
        - name: xtrabackup
          containerPort: 3307
        # 開始進行備份文件校驗、解析和開始同步
        command:
        - bash
        - "-c"
        - |
          set -ex
          cd /var/lib/mysql
          # Determine binlog position of cloned data, if any.
          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
            # XtraBackup already generated a partial "CHANGE MASTER TO" query
            # because we're cloning from an existing slave. (Need to remove the tailing semicolon!)
            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
            # Ignore xtrabackup_binlog_info in this case (it's useless).
            rm -f xtrabackup_slave_info xtrabackup_binlog_info
          elif [[ -f xtrabackup_binlog_info ]]; then
            # We're cloning directly from master. Parse binlog position.
            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
            rm -f xtrabackup_binlog_info xtrabackup_slave_info
            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
          fi
          # Check if we need to complete a clone by starting replication.
          if [[ -f change_master_to.sql.in ]]; then
            echo "Waiting for mysqld to be ready (accepting connections)"
            until mysql -h 127.0.0.1 -e "SELECT 1"; do sleep 1; done
            echo "Initializing replication from clone position"
            mysql -h 127.0.0.1 \
                  -e "$(<change_master_to.sql.in), \
                          MASTER_HOST='mysql-0.mysql', \
                          MASTER_USER='root', \
                          MASTER_PASSWORD='', \
                          MASTER_CONNECT_RETRY=10; \
                        START SLAVE;" || exit 1
            # In case of container restart, attempt this at-most-once.
            mv change_master_to.sql.in change_master_to.sql.orig
          fi
          # Start a server to send backups when requested by peers.
          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root"
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
      volumes:
      - name: conf
        emptyDir: {}
      - name: config-map
        configMap:
          name: mysql
  # 設置PVC
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 1Gi

主從節點的配置和啟動都在上面的yaml文件中定義好了,接下來需要逐個創建即可。

二、創建所需資源

//創建configMap
kubectl apply -f configMap.yaml
//創建service
kubectl apply -f service.yaml
//創建statefulSet
kubectl apply -f statefulSet.yaml

4.jpg
執行完畢後可以使用以下命令監測創建情況。

kubectl get pods --watch

5.jpg

三、測試主庫

1. 進入pod進行操作

進入到pod mysql-0中,進行測試

kubectl exec -it mysql-0 bash

2. 用mysql-client鏈接mysql-0

mysql -h mysql-0

3. 創建庫、表

//創建數據庫test
create database test;
//使用test庫
use test;
//創建message表
create table message (message varchar(50));
//查看message表結構
show create table message;

4. 插入數據

//插入
insert into message value("hello aloofjr");
//查看
select * from message;

6.jpg

四、測試備庫

1. 連接mysql-1

mysql -h mysql-1.mysql

2. 查看庫、表結構

//查看數據庫列表
show databases;
//使用test庫
use test;
//查看錶列表
show tables;
//查看message表結構
show create table message;

3. 讀取數據

//查看
select * from message;

4. 寫入數據

insert into message values("hello world");

此時會報錯 ERROR 1290 (HY000): The MySQL server is running with the --super-read-only option so it cannot execute this statement
這是因為mysql-1是一個只讀備庫,無法進行寫操作。
7.jpg

五、測試mysql-read服務

kubectl run mysql-client-loop --image=mysql:5.7 -i -t --rm --restart=Never --\
  bash -ic "while sleep 1; do mysql -h mysql-read -e 'SELECT @@server_id,NOW()'; done"

每秒查詢一次數據庫,可以觀察到,調度到不同的server-id,即pod節點
8.jpg

六、擴縮容

//擴容至5副本
kubectl scale statefulset mysql  --replicas=5
//縮容只2副本
kubectl scale statefulset mysql  --replicas=2

七、清理

kubectl delete statefulset mysql
kubectl delete configmap,service,pvc -l app=mysql

八、總結

上面就是通過k8s部署一個一主多從mysql集群的過程,其中有幾個重要知識點:

  • 通過configMap可以將配置和鏡像解耦
  • 通過initContainers在pod啟動前,做一些初始化工作
  • 通過requests設置pod所需的cpu和memory
  • 通過livenessProbe進行pod節點探活
  • 通過readnessProbe進行pod可用性檢測

本文中用到的yaml文件見我的GitHub倉庫AloofJr

阿里巴巴開源鏡像站 提供全面,高效和穩定的鏡像下載服務。釘釘搜索 ' 21746399 ‘ 加入鏡像站官方用戶交流群。”

Leave a Reply

Your email address will not be published. Required fields are marked *