redis.exceptions.ConnectionError on connecting to redis server in container

315 Views Asked by At

I have created a Dockerfile with following contents

FROM alpine

# Run commands to install additional software
RUN apk add --update redis

# Specify command to run when the container starts up
CMD ["redis-server"]

Then run docker build and run commands

docker build -t dkr/redis:latest .
docker run -p 6379:6379  dkr/redis

Then when I try to connect to redis server running in the container from the host machine, I get the following error. what is the correct way to connect to redis from host?

import redis
r = redis.Redis(host='127.0.0.1', port=6379, decode_responses=True)
>>> r.set("visits", "1")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/staging/venv/lib/python3.7/site-packages/redis/commands/core.py", line 2341, in set
    return self.execute_command("SET", *pieces, **options)
  File "/staging/venv/lib/python3.7/site-packages/redis/client.py", line 533, in execute_command
    conn = self.connection or pool.get_connection(command_name, **options)
  File "/staging/venv/lib/python3.7/site-packages/redis/connection.py", line 1086, in get_connection
    connection.connect()
  File "/staging/venv/lib/python3.7/site-packages/redis/connection.py", line 276, in connect
    self.on_connect()
  File "/staging/venv/lib/python3.7/site-packages/redis/connection.py", line 386, in on_connect
    self.read_response()
  File "/staging/venv/lib/python3.7/site-packages/redis/connection.py", line 500, in read_response
    response = self._parser.read_response(disable_decoding=disable_decoding)
  File "/staging/venv/lib/python3.7/site-packages/redis/_parsers/resp2.py", line 15, in read_response
    result = self._read_response(disable_decoding=disable_decoding)
  File "/staging/venv/lib/python3.7/site-packages/redis/_parsers/resp2.py", line 25, in _read_response
    raw = self._buffer.readline()
  File "/staging/venv/lib/python3.7/site-packages/redis/_parsers/socket.py", line 115, in readline
    self._read_from_socket()
  File "/staging/venv/lib/python3.7/site-packages/redis/_parsers/socket.py", line 68, in _read_from_socket
    raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
redis.exceptions.ConnectionError: Connection closed by server.
0

There are 0 best solutions below