创建部署文件
vim redis.yaml
添加如下内容:
apiVersion: v1
kind: Namespace
metadata:
name: redis
---
apiVersion: v1
kind: Secret
metadata:
name: redis-password
namespace: redis
type: Opaque
data:
password: d2d3cmhnZWE= # 建议生产环境使用更复杂的密码
---
apiVersion: v1
kind: ConfigMap
metadata:
name: redis-config
namespace: redis
data:
redis.conf: |
# 这里放置其他Redis配置,但移除了requirepass行
# 密码将通过命令行动态传入
maxmemory 256mb
maxmemory-policy allkeys-lru
appendonly yes
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis
namespace: redis
spec:
replicas: 1
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
spec:
containers:
- name: redis
image: redis:6.2
ports:
- containerPort: 6379
env:
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
name: redis-password
key: password
# 主要修改点在这里:通过命令行参数传递密码
command:
- "redis-server"
- "/usr/local/etc/redis/redis.conf"
- "--requirepass"
- "$(REDIS_PASSWORD)" # 这里会正确解析环境变量
volumeMounts:
- name: redis-config
mountPath: /usr/local/etc/redis/redis.conf
subPath: redis.conf
resources:
requests:
memory: "64Mi"
cpu: "100m"
limits:
memory: "256Mi"
cpu: "500m"
readinessProbe:
exec:
command:
- redis-cli
- -a
- $(REDIS_PASSWORD)
- ping
initialDelaySeconds: 5
periodSeconds: 10
volumes:
- name: redis-config
configMap:
name: redis-config
---
apiVersion: v1
kind: Service
metadata:
name: redis-service
namespace: redis
spec:
selector:
app: redis
ports:
- protocol: TCP
port: 6379
targetPort: 6379
# type: ClusterIP 是默认值,如果只在集群内部访问,无需修改
# 如果要从集群外部访问,可以改为 NodePort 或 LoadBalancer
# type: LoadBalancer
启动服务
kubectl apply -f redis.yaml
查看服务
kubectl get pods -n redis