How to resolve Redis connection error: ECONNREFUSED

Ruveyda
2 min readMay 7, 2023

--

Redis is a well-known in-memory data store that can serve as a database or cache. However, when trying to connect to Redis from your application, you might run into some issues. One common error is Cannot connect to Redis error. We’ll go over some of the possible causes of this problem in this post, along with some suggestions for fixing it.

I got this error 2 times in a row and each time forgot the solution. I had to write this blog in order not to forget the solution again :)

Main reasons for this error

Firstly, Redis may not be installed on your machine. If that’s the case, you need to install Redis before you can connect to it. You can check whether Redis is installed by running the following command in your terminal:

redis-cli ping

If you get an error saying command not found, then Redis is not installed on your machine. You can install Redis by following the instructions provided on the Redis website.

Secondly, Redis may not be currently running. You can check whether Redis is running by running the following command in your terminal:

If you get an error saying Could not connect to Redis at 127.0.0.1:6379: Connection refused, then Redis is not currently running. You can start Redis by running the following command in your terminal:

redis-server

If Redis is already running and you’re still getting the error message “Cannot connect to Redis”, it’s possible that you’re connecting to Redis from a host or port other than those where it is actually listening for connections.

If you’re running Redis locally or using a Docker image, you may need to adjust your host and port configuration accordingly.

  1. Running Redis locally: host= 127.0.0.1 and port= 6379
  2. Running Redis on Docker: host= <name of the Redis service in your docker-compose file> and port= 6379

This is a docker-compose file I’m currently using in one of my projects.

version: '3.9'

services:

# App service
app:
build:
# .
# .
# .

# Redis service
redis:
image: redis
ports:
- "6379:6379"
read_only: true
restart: unless-stopped

and this is my .env file:

REDIS_HOST=redis
REDIS_PORT=6379

The Redis host and port are set to redis and 6379 in the corresponding .env file, accordingly. Changing the Redis host in your .env to 127.0.0.1 will allow you to use your local Redis instead.

You should be able to fix the problem and build a successful connection to Redis by following the instructions in this post. Happy coding!

--

--

Ruveyda

Passionate about back-end development, sharing my knowledge and understanding as I learn.