k8s部署标准化MySQL

转载请注明出处

之前使用k8s部署了MySQL,但数据并没有做持久化,导致重启MySQL数据就丢了。
持久化数据以正常挂pv的方式会导致一直报容器没有常驻进程起不来的错误,使用subpath子目录挂载解决问题
在启用之前要先给用于挂载的本地服务器目录添加权限 chown -R mysql:mysql /path

部分mysql-deployment.yaml

        volumeMounts:
        - mountPath: /etc/mysql/my.cnf
          name: mysql-ini
          subPath: my.cnf
        - mountPath: /var/lib/init.sh
          name: script
          subPath: init.sh
        - mountPath: /data/mysql
          name: mysql-store
          subPath: mysqldata
# 初始化时pv不为空,使用子目录挂载解决这个问题
        command: ['/bin/bash', '-c', '/var/lib/init.sh;/usr/bin/mysqld_safe --user=mysql']
      volumes:
      - configMap:
          defaultMode: 420
          name: mysqlcnf
        name: mysql-ini
      - configMap:
          defaultMode: 511
          name: init
        name: script
      - name: mysql-store
        persistentVolumeClaim:
          claimName: mysql-chart-pvc

init.yaml

apiVersion: v1
data:
  init.sh: |-
    mkdir -p /home/mysql/;
    mkdir -p /data/mysql/data/;
    mkdir -p /data/mysql/log/;
    mkdir -p /data/mysql/run/;
    mkdir -p /data/mysql/tmp/;
    chown -R mysql:mysql /home/mysql;
    chown -R mysql:mysql /data/mysql/;
    /usr/sbin/mysqld --defaults-file=/etc/mysql/my.cnf --initialize-insecure --user=mysql --basedir=/data/mysql --datadir=/data/mysql/data &
kind: ConfigMap
metadata:
  name: init

myconf.yaml

apiVersion: v1
data:
  my.cnf: "[client] 
  port = 3306 
  socket = /data/mysql/tmp/mysql.sock 
  [mysqld]
    port = 3306 
    socket = /data/mysql/tmp/mysql.sock 
    basedir = /data/mysql
    datadir= /data/mysql/data 
    user = mysql
    server-id = 1 
    lc-messages-dir = /usr/share/mysql
    log-error=/data/mysql/log/mysqld.log
    pid-file=/data/mysql/run/mysqld.pid"
kind: ConfigMap
metadata:
  name: mysqlcnf

持久化数据pv

apiVersion: v1
kind: PersistentVolume
metadata:
  name: mysqlnfs
spec:
  accessModes:
  - ReadWriteOnce
  volumeMode: Filesystem
  capacity:
    storage: 10Gi
  persistentVolumeReclaimPolicy: Recycle
  storageClassName: slow
  nfs:
    path: /data/nfs
    server: ip

持久化数据pvc

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-chart-pvc
spec:
  accessModes:
    - ReadWriteOnce
  volumeMode: Filesystem
  resources:
    requests:
      storage: 10Gi
  storageClassName: slow
  volumeMode: Filesystem
  volumeName: mysqlnfs

初次登录mysql没有密码,直接mysql进入数据库
初次初始化mysql密码的语句/usr/bin/mysqladmin -u root password xxxxxx;

后续创建用户和密码需要用初始化的账号密码登录进去创建
create user 'username'@'host' identified by 'password';

Logo

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

更多推荐