通过 kubernetes 将 Flask 容器连接到 Redis 容器

问题描述 投票:0回答:1

我刚刚设置了一个 redis 实例,但是我似乎无法让两个容器相互通信,该设置可以使用 docker-compose 在本地计算机上运行,但似乎无法与 kubernetes 一起使用。

我的日志告诉我flask找不到服务,所以错误一定是我的配置文件

烧瓶代码:

rDB = redis.Redis(host='redis', port=6379, db=0)

Flask 服务器:

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: dashboard
  namespace: default
  labels:
    run: dashboard
spec:
  replicas: 2
  selector:
    matchLabels:
      run: dashboard
  template:
    metadata:
      labels:
        run: dashboard
    spec:
      containers:
      - image: gcr.io/******/dashboard_server:v102
        name: dashboard
        livenessProbe:
          httpGet:
            path: /
            port: 8000
          initialDelaySeconds: 300
          timeoutSeconds: 5
          periodSeconds: 300
          failureThreshold: 3
        ports:
          - containerPort: 8000
            name: http
            protocol: TCP

Redis 实例:

apiVersion: apps/v1 #  for k8s versions before 1.9.0 use apps/v1beta2  and before 1.8.0 use extensions/v1beta1
kind: Deployment
metadata:
  name: redis
  namespace: default
spec:
  selector:
    matchLabels:
      run: dashboard
      role: master
      tier: backend
  replicas: 1
  template:
    metadata:
      labels:
        run: dashboard
        role: master
        tier: backend
    spec:
      containers:
      - name: redis
        image: redis  # or just image: redis
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
        ports:
        - containerPort: 6379

服务代码

apiVersion: v1
kind: Service
metadata:
  name: dash-service
  namespace: default
  labels:
    run: frontend
spec:
  selector:
    run: dashboard
  ports:
    - name: http
      protocol: TCP
      port: 80
      targetPort: 8000
  type: ClusterIP
docker flask kubernetes redis
1个回答
6
投票

这是我在 K8s 内创建 Redis 集群的服务。

apiVersion: v1
kind: Service
metadata:
  labels:
    app: redis
  name: my-redis-svc
  namespace: default
spec:
  ports:
  - name: redis
    port: 6379
    targetPort: 6379
    protocol: TCP
  selector:
    app: redis
  type: ClusterIP

如果您创建该服务,您的 Pod 应该可以被同一命名空间中使用该主机名的其他 Pod 访问:

my-redis-svc.default.svc.cluster.local

这意味着,在您的应用程序代码中,您必须更改该行:

rDB = redis.Redis(host='my-redis-svc.default.svc.cluster.local', port=6379, db=0)
© www.soinside.com 2019 - 2024. All rights reserved.