Many of you may find a common error Error: connect ECONNREFUSED 127.0.0.1:6379 in docker-compose while connecting Redis with Node.js. In this article, I am going to show you how to fix this issue.
When working with Docker, the default host won’t suffice, and your container name becomes the host. In your case, it’s “client.” To connect with Redis, adjust your code as follows:
Using the socket configuration:
const client = redis.createClient({ socket: { port: 6379, host: 'client' } });
Alternatively, using the URL configuration:
const client = redis.createClient({ url: 'redis://client:6379' });
This ensures that your Redis client communicates correctly within the Docker environment, recognizing “client” as the host name.
Alternative way
docker-compose.yaml File:
- You have a
docker-compose.yaml
file, which is a configuration file for Docker Compose. This file defines the services, networks, and volumes for your application. - Within this file, you have services named “redis” and “app” (assuming these are the service names based on your
docker-compose up -d
commands).
services: redis: # ... (configuration for the Redis service) app: # ... (configuration for the app service)
Starting Services:
- You use the
docker-compose up -d
command to start Docker Compose services in detached mode (“-d”). This means the services run in the background.
docker-compose up -d redis docker-compose up -d app
- These commands start the “redis” and “app” services defined in your
docker-compose.yaml
file.
const client = redis.createClient({ url: 'redis://redis' });
- Here,
redis://
indicates the Redis protocol, and ‘redis’ is the host name. - The reason you don’t need to specify the port in the URL is that the default Redis port (6379) is assumed when not provided.
By following this setup, your Node.js application can communicate with the Redis service using the specified connection URL, and Docker Compose manages the networking and service discovery behind the scenes.