python - 将 Python 应用程序连接到 Kubernetes 集群上的 Redis

标签 python docker redis kubernetes

一个带有小型 Python 应用程序的 docker 容器被部署到一个 Kubernetes 集群,该集群有一个 redis master 和一个 redis slave 服务在集群中运行。 Docker 容器内的 Python 应用程序无法跨集群连接到 redis,因为 Python 应用程序未正确配置以在网络上查找 redis

为了使 app.py 中的 Python 应用程序能够与运行在同一个集群?

Python 应用程序代码

这里是app.py

from flask import Flask
from redis import Redis, RedisError
import os
import socket

# Connect to Redis
redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)

app = Flask(__name__)

@app.route("/")
def hello():
    try:
        visits = redis.incr("counter")
    except RedisError:
        visits = "<i>cannot connect to Redis, counter disabled</i>"

    html = "<h3>Hello {name}!</h3>" \
        "<b>Hostname:</b> {hostname}<br/>" \
        "<b>Visits:</b> {visits}"
    return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)


在同一个 KUBERNETES 集群中的 REDIS 服务

集群中运行的redis masterredis slave来自公共(public)注册中心,通过运行kubectl apply -f引入集群使用以下 JSON:

Redis 主复制 Controller JSON from this link.
Redis Master服务JSON from this link.
Redis Slave 复制 Controller JSON from this link.
Redis Slave 服务 JSON from this link.

最佳答案

What specific changes need to be made to the code below in order for the python app in app.py to be able to communicate successfully with the redis running in the same cluster?

redis = Redis(host="redis-master", db=0, socket_connect_timeout=2, socket_timeout=2)

因为您安装的Service 名为redis-master ,尽管我在上面提出的那个简单更改假设 flask 应用程序在与 redis-master Service 相同的 kubernetes 命名空间中运行。如果不是这样,您需要将其切换为阅读:

redis = Redis(host="redis-master.whatever-namespace.svc.cluster.local",

并将 whatever-namespace 替换为实际的、正确的命名空间。如果您不记得或不知道,kubectl get --all-namespaces=true svc | grep redis-master 会提醒你。

关于python - 将 Python 应用程序连接到 Kubernetes 集群上的 Redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51331730/

相关文章:

python - PyQt 清除菜单栏

python - 如何找到数据框特定列值的不同计数

python - 如何改进评估列表以确定其是否包含特定连续项目的方法?

docker - 锁定Docker注册表

docker - 在 Windows 主机上的 docker 容器中运行 cron

python - 是否可以在事件循环已在运行时运行 asyncio.Server 实例

docker docker-compose 另一个容器中的 nginx 根目录

go - channel 卡住的 TCP 到 Redis 服务器

基于 Redis 的 Java 作业调度程序?

ruby-on-rails - 在初始化程序中设置 cache_store