K8s 如何通过 ConfigMap 来配置 Redis ?

本文演示了如何在Kubernetes环境下创建ConfigMap,用于配置Redis实例的maxmemory和maxmemory-policy。首先创建空的ConfigMap,接着创建RedisPod并挂载ConfigMap,然后更新ConfigMap添加配置,最后验证Redis是否应用了新的配置。通过这个过程,读者能了解ConfigMap在实际应用中的用法。

k8s-cert


1、创建 ConfigMap YAML 配置文件

cat <<EOF >./example-redis-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: example-redis-config
data:
  redis-config: ""
EOF

2、创建 ConfigMap 资源

kubectl apply -f example-redis-config.yaml

创建完成后查看是否成功创建。

image-20230116143158080

这是创建了一个空的 ConfigMap 资源,看其详情:

image-20230116143911680

3、创建 Redis 的 Pod 资源

vim redis.yml
apiVersion: v1

kind: Pod
metadata:
  name: redis

spec:
  containers:
  - name: redis
    image: redis:5.0.4
    command:
      - redis-server
      - "/redis-master/redis.conf"
    env:
    - name: MASTER
      value: "true"
    ports:
    - containerPort: 6379
    resources:
      limits:
        cpu: "0.1"
    volumeMounts:
    - mountPath: /redis-master-data
      name: data
    - mountPath: /redis-master
      name: config
  volumes:
    - name: data
      emptyDir: {}
    - name: config
      configMap:
        name: example-redis-config
        items:
        - key: redis-config
          path: redis.conf

上面的参数应该就不陌生了,相信大家都明白,如果还不太清楚的,可以去看看 Secret、ConfigMap 相关的知识。

kubectl apply -f redis.yml
kubectl get pod

image-20230116143349691

4、进入 redis Pod 并查看 redis 资源

kubectl exec -it redis -- redis-cli
config get maxmemory
config get maxmemory-policy

image-20230116144215129

可看到值都是返回默认值-不符合我们的需求,现在往配置文件中添加数据,然后再次进行验证。

5、添加配置

cat <<EOF >./example-redis-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: example-redis-config
data:
  redis-config:
    maxmemory 2mb
    maxmemory-policy allkeys-lru
EOF

更新完成后再次更新 ConfigMap 资源。

kubectl apply -f example-redis-config.yaml
kubectl describe configmap example-redis-config

image-20230116145027908

6、通过 kubectl exec 使用 redis-cli 再次检查 Redis Pod,查看是否已应用配置

  • 先重启 Redis Pod 才能生效

    # 删除Pod
    kubectl delete pod redis
    
    # 创建Pod
    kubectl apply -f redis.yml
    

    image-20230116145913059

  • 再次验证

    kubectl exec -it redis -- redis-cli
    
    config get maxmemory
    config get maxmemory-policy
    

    image-20230116150146826

7、实验完成,删除资源

kubectl delete pod/redis configmap/example-redis-config

image-20230116150406885

小结:看这篇文章的前提是你已经基本掌握 ConfigMap 的概念及在实际测试/生产中的应用,重点还是搞清概念,其他的都很简单。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云计算-Security

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值