Timeout connecting to Redis Cluster running in Docker from Python script

I'm trying to connect to a Redis Cluster running in Docker containers from a Python script on my Windows machine. I am able to establish the initial connection to the cluster, but when performing any further operations, I receive a timeout error. Below is the configuration and part of the script I'm using.

Environment Details:

Error Message:

Conexión al Redis Cluster establecida correctamente.
Error al conectarse al Redis Cluster: Timeout connecting to server

Python Script:

import rediscluster
import time

# Configuración de los nodos del Redis Cluster
startup_nodes = [
    {"host": "host.docker.internal", "port": 7001},
    {"host": "host.docker.internal", "port": 7002},
    {"host": "host.docker.internal", "port": 7003}
]

# Conectar al Redis Cluster
retries = 3  # Número de intentos de reconexión
for attempt in range(retries):
    try:
        redis_cluster = rediscluster.RedisCluster(
            startup_nodes=startup_nodes,
            decode_responses=True,
            skip_full_coverage_check=True,
            socket_connect_timeout=60,  # Incrementar el tiempo de espera de conexión a 60 segundos
            socket_timeout=120,  # Incrementar el tiempo de espera para las operaciones a 120 segundos
            retry_on_timeout=True  # Habilitar reintento en caso de timeout
        )
        print("Conexión al Redis Cluster establecida correctamente.")
        break
    except Exception as e:
        print(f"Error al conectarse al Redis Cluster (intento {attempt + 1}/{retries}): {e}")
        if attempt == retries - 1:
            raise
        time.sleep(5)  # Esperar 5 segundos antes de reintentar

# Verificar el estado del cluster antes de realizar operaciones
try:
    cluster_info = redis_cluster.cluster_info()
    if cluster_info.get('cluster_state') != 'ok':
        raise Exception("El estado del cluster no es 'ok'. Verifique la configuración del cluster.")

    # Ejemplo de operación usando un nodo maestro
    redis_cluster.set("clave", "valor")
    print("Valor de 'clave':", redis_cluster.get("clave"))

except Exception as e:
    print(f"Error durante la operación en el Redis Cluster: {e}")

**How I Created the Cluster Nodes and Connected Them:

To create the Redis Cluster nodes, I used the following commands to start three separate Docker containers, each running a Redis instance:

docker run -d --name redis-node1 --net redis-cluster-network -p 7001:6379 redis:7.0 redis-server --port 6379 --cluster-enabled yes --cluster-config-file nodes.conf --cluster-node-timeout 5000 --appendonly yes

docker run -d --name redis-node2 --net redis-cluster-network -p 7002:6379 redis:7.0 redis-server --port 6379 --cluster-enabled yes --cluster-config-file nodes.conf --cluster-node-timeout 5000 --appendonly yes

docker run -d --name redis-node3 --net redis-cluster-network -p 7003:6379 redis:7.0 redis-server --port 6379 --cluster-enabled yes --cluster-config-file nodes.conf --cluster-node-timeout 5000 --appendonly yes

Once the nodes were running, I used the following command to create the cluster and assign slots to each node:

redis-cli --cluster create 172.18.0.2:6379 172.18.0.3:6379 172.18.0.4:6379 --cluster-replicas 0

I mapped the container ports to my local machine (7001, 7002, 7003) and used host.docker.internal to connect to them from the host system.

What I've Tried:

  1. Increasing the socket_connect_timeout and socket_timeout values.
  2. Verifying the state of the Redis cluster to ensure it's ok before performing operations.
  3. Mapping Docker container ports (7001, 7002, 7003) to my local machine and using host.docker.internal as the hostname.
  4. Verifying that each Redis node has the correct slot coverage using cluster nodes and cluster slots commands.

Docker Logs:

2024-11-19 11:14:01 1:C 19 Nov 2024 17:14:01.843 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
2024-11-19 11:14:01 1:C 19 Nov 2024 17:14:01.843 # Redis version=7.0.15, bits=64, commit=00000000, modified=0, pid=1, just started
2024-11-19 11:14:01 1:C 19 Nov 2024 17:14:01.843 # Configuration loaded
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.844 * monotonic clock: POSIX clock_gettime
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.844 * No cluster configuration found, I'm 39fa992aad12f83ca4ea684d0a20ee9202e4288b
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.852 * Running mode=cluster, port=6379.
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.857 # Server initialized
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.861 * Creating AOF base file appendonly.aof.1.base.rdb on server start
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.868 * Creating AOF incr file appendonly.aof.1.incr.aof on server start
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.868 * Ready to accept connections
2024-11-19 11:16:43 1:M 19 Nov 2024 17:16:43.524 # configEpoch set to 2 via CLUSTER SET-CONFIG-EPOCH
2024-11-19 11:16:43 1:M 19 Nov 2024 17:16:43.691 # IP address for this node updated to 172.18.0.3
2024-11-19 11:16:48 1:M 19 Nov 2024 17:16:48.535 # Cluster state changed: ok

Question: Why do I keep getting a timeout error when performing operations, even though the initial connection is successful? Could there be any misconfiguration in the cluster setup or something I'm missing in the Python code? Any help would be greatly appreciated!

Upvotes: 0

Views: 33

Answers (0)

Related Questions