Getting Error: connect ECONNREFUSED 127.0.0.1:6379 in docker-compose while connecting redis
Asked Answered
P

6

6

I am getting connection Error: connect ECONNREFUSED 127.0.0.1:6379 while working with docker-compose to use Redis with node js. I used the same host name and service name in Redis but still got an error.

My node js code is:

const express = require('express');
const redis = require('redis');

const client = redis.createClient({
    port: 6379,
    host: 'redis'
});
client.connect();
client.on('connect', (err)=>{
    if(err) throw err;
    else console.log('Redis Connected..!');
});

const app = express();
app.get('/',async (req,res)=>{
    let key = req.query['name'];
    if(key){
        let value = await client.get(key);
        if(value){
            value++;
            client.set(key,value);
            res.send(`Hello ${key}, ${value}!`);
            console.log(`${key}, ${value}`);
        }
        else{
            value = 1;
            client.set(key,value); 
            res.send(`Hello ${key}, ${value}!`);
            console.log(`${key}, ${value}`);
        }
    }
    else{
        console.log("Name not passed!");
        res.send("Hello World!");
    }
});
const port = 3000;
app.listen(port,()=>{
    console.log(`App is listening at http://localhost:${port}`);
});

My docker-compose.yml file is:

version: "3"
services:
  redis: 
    image: redis:latest
    container_name: client
    restart: unless-stopped
    expose:
      - 6379
  app:
    depends_on:
      - redis
    build:
      context: .
      dockerfile: Dockerfile
    container_name: app
    restart: on-failure
    ports:
      - "3000:3000"
    volumes:
      - .:/app

and what I am getting on console is

C:\Users\ashok\Desktop\Practice>docker-compose up
[+] Running 3/3
 - Network practice_default  Created                                                                                                        0.1s
 - Container client          Created                                                                                                        1.1s
 - Container app             Created                                                                                                        0.3s
Attaching to app, client
client  | 1:C 02 Apr 2022 11:08:28.885 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
client  | 1:C 02 Apr 2022 11:08:28.886 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
client  | 1:C 02 Apr 2022 11:08:28.886 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
client  | 1:M 02 Apr 2022 11:08:28.889 * monotonic clock: POSIX clock_gettime
client  | 1:M 02 Apr 2022 11:08:28.890 * Running mode=standalone, port=6379.
client  | 1:M 02 Apr 2022 11:08:28.891 # Server initialized
client  | 1:M 02 Apr 2022 11:08:28.891 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
client  | 1:M 02 Apr 2022 11:08:28.893 * Ready to accept connections
app     |
app     | > [email protected] start
app     | > node app.js
app     |
app     | Server is live at port: 3000
app     | node:internal/process/promises:279
app exited with code 1
app     |             triggerUncaughtException(err, true /* fromPromise */);
app     |             ^
app     |
app     | Error: connect ECONNREFUSED 127.0.0.1:6379
app     |     at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16)
app     | Emitted 'error' event on Commander instance at:
app     |     at RedisSocket.<anonymous> (/app/node_modules/@node-redis/client/dist/lib/client/index.js:339:14)
app     |     at RedisSocket.emit (node:events:527:28)
app     |     at RedisSocket._RedisSocket_connect (/app/node_modules/@node-redis/client/dist/lib/client/socket.js:117:14)
app     |     at processTicksAndRejections (node:internal/process/task_queues:96:5)
app     |     at async Commander.connect (/app/node_modules/@node-redis/client/dist/lib/client/index.js:162:9) {
app     |   errno: -111,
app     |   code: 'ECONNREFUSED',
app     |   syscall: 'connect',
app     |   address: '127.0.0.1',
app     |   port: 6379
app     | }

what can I do to resolve it?

Pettifogging answered 2/4, 2022 at 12:6 Comment(1)
It looks like redis.createClient() doesn't directly accept host: as a parameter; either it wants a url:, or it wants the host: and port: inside a socket: object. (Configuring it to point at redis is correct in a Compose context, but that shouldn't resolve to 127.0.0.1.) Does changing the createClient() call help?Nureyev
B
15

I had tried specifying host and port in the client creation too, and that didn't work. I found that using

const client = redis.createClient({
url: 'redis://redis:6379'
});

fixed the issue for me.

Brannen answered 18/5, 2022 at 15:30 Comment(0)
H
8

You are using docker, so the default host will not work and the container name will be your host which is client in your case. So if you want to connect with Redis then you have to do something like this -

const client = redis.createClient({
    socket: {
       port: 6379,
       host: 'client'
    }
});

// OR

const client = redis.createClient({
    url: 'redis://client:6379'
});
Hermosa answered 20/12, 2022 at 18:2 Comment(0)
E
2

I faced the same issue, but solution is

let redisClient = redis.createClient({
  url: 'redis://redis:6379',
  legacyMode: true,
});
Endorsee answered 18/8, 2022 at 9:5 Comment(0)
B
0

For me this work perfectly.

In docker-compose.yaml

docker-compose up -d redis
docker-compose up -d app

Don't need write the port in connection url.

redis.createClient({
    url: 'redis://redis'
});
Bit answered 17/2, 2023 at 7:42 Comment(0)
R
0

I found that using the container_name for Redis fixed the problem.

So, in ".env" I have:

REDIS_HOST=service-redis

Rottenstone answered 27/8, 2023 at 8:51 Comment(0)
A
0

Using the container name instead of localhost for the redis host also worked for me.

Azoth answered 22/5 at 0:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.