mysql-slave-v4.yaml 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. apiVersion: v1
  2. kind: ConfigMap
  3. metadata:
  4. name: mysql-slave-config
  5. data:
  6. my.cnf: |
  7. [mysqld]
  8. server-id=2
  9. relay-log=mysql-relay-bin
  10. log-bin=mysql-bin
  11. binlog-format=ROW
  12. gtid-mode=ON
  13. enforce-gtid-consistency=ON
  14. skip-replica-start=ON
  15. default-authentication-plugin=mysql_native_password
  16. bind-address=0.0.0.0
  17. # 注意:不要在这里设置 read_only 或 super_read_only
  18. # 这些应该在复制配置完成后再设置
  19. ---
  20. apiVersion: v1
  21. kind: Service
  22. metadata:
  23. name: mysql-slave
  24. labels:
  25. app: mysql
  26. role: slave
  27. spec:
  28. ports:
  29. - port: 3306
  30. name: mysql
  31. selector:
  32. app: mysql
  33. role: slave
  34. ---
  35. apiVersion: apps/v1
  36. kind: Deployment
  37. metadata:
  38. name: mysql-slave
  39. labels:
  40. app: mysql
  41. role: slave
  42. spec:
  43. replicas: 1
  44. selector:
  45. matchLabels:
  46. app: mysql
  47. role: slave
  48. template:
  49. metadata:
  50. labels:
  51. app: mysql
  52. role: slave
  53. spec:
  54. containers:
  55. - name: mysql
  56. image: mysql:8.0.44
  57. env:
  58. - name: MYSQL_ROOT_PASSWORD
  59. value: "Lq123456!"
  60. ports:
  61. - containerPort: 3306
  62. volumeMounts:
  63. - name: config
  64. mountPath: /etc/mysql/conf.d/
  65. resources:
  66. requests:
  67. memory: "512Mi"
  68. cpu: "250m"
  69. lifecycle:
  70. postStart:
  71. exec:
  72. command:
  73. - /bin/bash
  74. - -c
  75. - |
  76. # 等待MySQL完全启动
  77. echo "等待MySQL启动..."
  78. for i in {1..30}; do
  79. if mysql -uroot -pLq123456! -e "SELECT 1" &>/dev/null; then
  80. echo "MySQL已启动"
  81. break
  82. fi
  83. echo "等待MySQL... ($i/30)"
  84. sleep 2
  85. done
  86. # 配置复制
  87. echo "配置主从复制..."
  88. mysql -uroot -pLq123456! <<EOF
  89. STOP REPLICA;
  90. RESET REPLICA ALL;
  91. CHANGE REPLICATION SOURCE TO
  92. SOURCE_HOST='mysql-master',
  93. SOURCE_USER='replica',
  94. SOURCE_PASSWORD='Replica123456!',
  95. SOURCE_AUTO_POSITION=1;
  96. START REPLICA;
  97. EOF
  98. # 设置只读模式
  99. echo "设置只读模式..."
  100. mysql -uroot -pLq123456! -e "SET GLOBAL read_only = ON; SET GLOBAL super_read_only = ON;"
  101. echo "配置完成"
  102. mysql -uroot -pLq123456! -e "SHOW REPLICA STATUS\G" | grep -E "Replica_IO_Running|Replica_SQL_Running"
  103. volumes:
  104. - name: config
  105. configMap:
  106. name: mysql-slave-config