StatefulSet介绍
暂时略...
实战案例
1. 准备启动redis-server 运行脚本
$ cat launch.sh
#!/bin/bash
PASSWORD=$(cat /etc/redis-passwd/passwd)
#StatefulSet会给每个POD分配一个固定的主机网络标识符号,所以这里可以通过主机名去判断主节点
if [ "${HOSTNAME}" == "redis-0" ]
then
redis-server --requirepass ${PASSWORD}
else
redis-server --slaveof redis-0.redis 6379 --masterauth ${PASSWORD} --requirepass ${PASSWORD}
fi
2. 创建ConfigMap和密码配置Secret
#secret对象存放密码
$ kubectl create secret generic redis-passwd --from-literal=passwd="password"
#configmap对象存放运行脚本
$ kubectl delete configmap redis-config
$ kubectl create configmap redis-config --from-file=launch.sh=launch.sh
$ kubectl get configmap
$ kubectl get configmap redis-config -o yaml
3. 创建Headless Service
$ cat headless-service.yaml
apiVersion: v1
kind: Service
metadata:
name: "redis"
labels:
app: redis
spec:
ports:
- port: 6379
name: redis
clusterIP: None
selector:
app: redis
4. 创建Statefulset
$ cat statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: redis
namespace: default
spec:
serviceName: "redis"
replicas: 3
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
spec:
containers:
- name: redis
image: redis:5-alpine
ports:
- containerPort: 6379
name: redis
volumeMounts:
- name: data
mountPath: /data
- name: script
mountPath: /script/launch.sh
subPath: launch.sh
- name: passwd-volume
mountPath: /etc/redis-passwd
command:
- sh
- -c
- sleep 10 && sh /script/launch.sh #这里解释下,我在本地测试环境如果不加sleep,启动redis之后会提示找不到/script/launch.sh,我不知道是不是延迟挂载之类,暂时先管,跑起来再说
volumes:
- name: script
configMap:
name: redis-config
defaultMode: 0777
- name: passwd-volume
secret:
secretName: redis-passwd
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
5. 检查
#每个POD是否被正确分配网络标识
$ kubectl run -i --tty --image busybox:1.28 dns-test --restart=Never --rmkub
If you don't see a command prompt, try pressing enter.
/ # nslookup redis-0.redis
Server: 10.96.0.10
Address 1: 10.96.0.10 kube-dns.kube-system.svc.cluster.local
Name: redis-0.redis
Address 1: 10.244.1.112 redis-0.redis.default.svc.cluster.local
/ #
主从环境是否正常初始化