【容器应用系列教程】Kubernetes有状态负载StatefulSet
一、StatefulSet
介绍
- 本质上就是
POD
- 特性
- 重建
POD
时,会自动挂载之前的数据卷 - 依赖于网络存储的数据卷
- 重建
- 适用场景:适用于数据库
二、创建StatefulSet
1.创建PV
和PVC
创建过程省略
关于PV
和PVC
的创建教程:https://www.wsjj.top/archives/144
[root@k8s-master opt]# kubectl get pv -n default
NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE
nfs-pv1 1900M RWX Recycle Available 15h
nfs-pv2 4G RWX Recycle Bound default/test-pvc 15h
[root@k8s-master opt]# kubectl get pvc -n default
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
test-pvc Bound nfs-pv2 4G RWX 14h
2.创建有状态负载StatefulSet
[root@k8s-master opt]# vim state-mysql.yml
apiVersion: apps/v1
kind: StatefulSet #类型为有状态负载
metadata:
name: mysql
spec:
replicas: 1
selector:
matchLabels:
app: mysql
serviceName: "mysql" #此处需要绑定服务名,这个服务名对应着下面的Service
template:
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:5.7
imagePullPolicy: IfNotPresent
env:
- name: MYSQL_ROOT_PASSWORD
value: redhat
volumeMounts:
- name: mysql-volume
mountPath: /var/lib/mysql #配置永久挂载数据目录
volumes:
- name: mysql-volume #创建个数据卷
persistentVolumeClaim: #挂载PVC
claimName: test-pvc
---
apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
ports:
- port: 3306
selector:
app: mysql
[root@k8s-master opt]# kubectl get pods -n default
NAME READY STATUS RESTARTS AGE
mysql-0 1/1 Running 0 153m
进入数据库创建测试数据
[root@k8s-master opt]# kubectl exec -it mysql-0 -n default -- bash
bash-4.2# mysql -uroot -predhat
mysql> create database AAA;
Query OK, 1 row affected (0.01 sec)
mysql> create database BBB;
Query OK, 1 row affected (0.00 sec)
mysql> create database CCC;
Query OK, 1 row affected (0.01 sec)
查看NFS
共享目录
[root@k8s-nfs ~]# ls /data2
auto.cnf ib_buffer_pool mysql server-cert.pem
ca-key.pem ibdata1 mysql.sock server-key.pem
ca.pem ib_logfile0 performance_schema sys
client-cert.pem ib_logfile1 private_key.pem
client-key.pem ibtmp1 public_key.pem
删除Pod
模拟故障
[root@k8s-master opt]# kubectl delete pod mysql-0 -n default
pod "mysql-0" deleted
Pod
会自动创建
并且名字和被删除的
Pod
名字一样
[root@k8s-master ~]# kubectl get pods -n default
NAME READY STATUS RESTARTS AGE
mysql-0 0/1 Terminating 0 155m
[root@k8s-master ~]# kubectl get pods -n default
NAME READY STATUS RESTARTS AGE
mysql-0 0/1 ContainerCreating 0 1s
[root@k8s-master ~]# kubectl get pods -n default
NAME READY STATUS RESTARTS AGE
mysql-0 1/1 Running 0 2s
再次查看NFS
共享目录
文件没有丢失
[root@k8s-nfs ~]# ls /data2
auto.cnf ib_buffer_pool mysql server-cert.pem
ca-key.pem ibdata1 mysql.sock server-key.pem
ca.pem ib_logfile0 performance_schema sys
client-cert.pem ib_logfile1 private_key.pem
client-key.pem ibtmp1 public_key.pem
登录数据库查看库
刚才创建的库还存在
[root@k8s-master opt]# kubectl exec -it mysql-0 -n default -- bash
bash-4.2# mysql -uroot -predhat
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| AAA |
| BBB |
| CCC |
| mysql |
| performance_schema |
| sys |
+--------------------+
7 rows in set (0.01 sec)