To connect to Redis in Kubernetes, you need to set up a Redis deployment and service. This can be achieved using Kubernetes manifests (YAML files). Following are the steps to create a simple Redis deployment and service, and then access it from another application within the cluster.
Create a Redis Deployment
Create a YAML file redis-deployment.yaml
with the following content:
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis
spec:
selector:
matchLabels:
app: redis
replicas: 1
template:
metadata:
labels:
app: redis
spec:
containers:
- name: redis
image: redis:latest
ports:
- containerPort: 6379
Apply the Deployment
Run the following command to apply the configuration and create the deployment:
kubectl apply -f redis-deployment.yaml
Create a Redis Service
To expose Redis within the cluster, create a YAML file redis-service.yaml
with the following content:
apiVersion: v1
kind: Service
metadata:
name: redis
spec:
selector:
app: redis
ports:
- protocol: TCP
port: 6379
targetPort: 6379
Apply the Service
Run the following command to apply the configuration and create the service:
kubectl apply -f redis-service.yaml
Access Redis from Another Application
Now that Redis is running as a service within your Kubernetes cluster, you can connect to it from another application using the service name redis
as the hostname and port 6379
. Here's an example using Python with the redis
library:
import redis
# Connect to Redis
r = redis.Redis(host='redis', port=6379)
# Set a key-value pair
r.set('my_key', 'Hello, Redis!')
# Get the value of the key
value = r.get('my_key')
print(value.decode('utf-8'))
By following these steps, you have successfully connected to Redis in Kubernetes.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.