发布于 

Kubernetes集群部署Redis单机版

创建 ConfigMap

我们可以通过 ConfigMap 来对容器中 redis 应用的配置进行管理,如自定义配置文件、密码、日志路径等。

singlenode-redis-conf.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
apiVersion: v1
kind: ConfigMap
metadata:
name: singlenode-redis-conf
data:
redis.conf: |
bind 0.0.0.0
port 6379
requirepass 123456
pidfile .pid
appendonly yes
cluster-config-file nodes-6379.conf
pidfile /data/k8s/redis/log/redis-6379.pid
cluster-config-file /data/k8s/redis/conf/redis.conf
dir /data/k8s/redis/data/
logfile "/data/k8s/redis/log/redis-6379.log"
cluster-node-timeout 5000
protected-mode no

执行以下命令创建 ConfigMap:

创建 StatefulSet

由于 redis 是一个有状态服务,所以需要创建一个 StatefulSet,并把数据挂载到宿主机上。

singlenode-redis-statefulset.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: singlenode-redis
spec:
replicas: 1
serviceName: singlenode-redis
selector:
matchLabels:
name: singlenode-redis
template:
metadata:
labels:
name: singlenode-redis
spec:
initContainers:
- name: init-singlenode-redis
image: busybox
command: ['sh', '-c', 'mkdir -p /data/k8s/redis/log/; mkdir -p /data/k8s/redis/conf/; mkdir -p /data/k8s/redis/data/']
volumeMounts:
- name: data
mountPath: /data/k8s/redis/
containers:
- name: singlenode-redis
image: redis:5.0.6
imagePullPolicy: IfNotPresent
command:
- sh
- -c
- "exec redis-server /data/k8s/redis/conf/redis.conf"
ports:
- containerPort: 6379
name: redis
protocol: TCP
volumeMounts:
- name: redis-config
mountPath: /data/k8s/redis/conf/
- name: data
mountPath: /data/k8s/redis/
volumes:
- name: redis-config
configMap:
name: singlenode-redis-conf
- name: data
hostPath:
path: /data/k8s/redis/

执行以下命令创建 StatefulSet:

查看 pod 运行状况:

创建 Service

通过创建 service,提供对外访问 pod 的服务接口。

singlenode-redis-service.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
apiVersion: v1
kind: Service
metadata:
name: singlenode-redis
labels:
name: singlenode-redis
spec:
type: NodePort
ports:
- name: singlenode-redis
port: 6379
targetPort: 6379
nodePort: 31379
selector:
name: singlenode-redis

执行以下命令创建 Service:

查看 service 运行状况:

验证 redis 是否部署成功

我这里使用的是 Redis Desktop Manager 客户端连接验证,下载地址:https://macwk.com/soft/redis-desktop-manager

redis测试连接
redis测试连接
redis连接成功
redis连接成功