A docker container with a small Python app inside it is deployed to a Kubernetes cluster that has a redis master
and a redis slave
service running in the cluster. The Python app inside the Docker container is not able to connect to the redis
across the cluster because the Python app is not configured properly to find redis
on the network.
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?
PYTHON APP CODE
Here is 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)
REDIS SERVICES IN THE SAME KUBERNETES CLUSTER
The redis master
and redis slave
running in the cluster are from public registries and are brought into the cluster by running kubectl apply -f
with the following JSON:
Redis Master replication controller JSON from this link.
Redis Master service JSON from this link.
Redis Slave replication controller JSON from this link.
Redis Slave service JSON from this link.