Rohit
Rohit

Reputation: 23

Connection refused when connecting to redis on EC2 instance

I am trying to connect to local redis database on EC2 instance from a lambda function. However when I try to execute the code, I get the following error in the logs

{
    "errorType": "Error",
    "errorMessage": "Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379",
    "code": "ECONNREFUSED",
    "stack": [
        "Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379",
        "    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)"
    ],
    "errno": "ECONNREFUSED",
    "syscall": "connect",
    "address": "127.0.0.1",
    "port": 6379
}

The security group has the following entries

Type: Custom TCP Rule
Port: 6379
Source: <my security group name>

Type: Custom TCP Rule
Port: 6379
Source: 0.0.0.0/0

My Lambda function has the following code.

'use strict';
const Redis = require('redis');

module.exports.hello = async event => {
  var redis = Redis.createClient({
      port: 6379,
      host: '127.0.0.1',
      password: ''
    });

  redis.on('connect', function(){
    console.log("Redis client conected : " );   
  });

  redis.set('age', 38, function(err, reply) {
    console.log(err);
    console.log(reply);
  });

  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'The lambda function is called..!!',
        input: event,
        redis: redis.get('age')
      },
      null,
      2
    ),
  };

};

Please let me know where I am going wrong.

Upvotes: 2

Views: 6362

Answers (2)

Leigh Mathieson
Leigh Mathieson

Reputation: 2018

On Linux Ubuntu server 20.04 LTS I was seeing a similar error after reboot of the EC2 server which for our use case runs an express app via a cron job connecting a nodeJs app (installed with nvm) using passport.js to use sessions in Redis:

Redis error: Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16) { errno: 'ECONNREFUSED', code: 'ECONNREFUSED', syscall: 'connect', address: '127.0.0.1', port: 6379 }

What resolved it for me, as my nodeJs app was running as Ubuntu user I needed to make that path available, was to add to the PATH within /etc/crontab by:

sudo nano /etc/crontab Just comment out the original path in there so you can switch back if required (my original PATH was set to: PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin ) and append the location of your bin you may need to refer to, in the format:

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/home/ubuntu/.nvm/versions/node/v12.20.0/bin

And the error disappeared for me

// redisInit.js

const session = require('express-session');
const redis = require('redis');
const RedisStore = require('connect-redis')(session);

const { redisSecretKey } = process.env;

const redisClient = redis.createClient();

redisClient.on('error', (err) => {
    console.log('Redis error: ', err);
});

const redisSession = session({
    secret: redisSecretKey,
    name: 'some_redis_store_name',
    resave: true,
    saveUninitialized: true,
    cookie: { secure: false },
    store: new RedisStore(
        {
            host: 'localhost', port: 6379, client: redisClient, ttl: 86400
        }
    )
});

module.exports = redisSession;

Upvotes: 0

Adiii
Adiii

Reputation: 59896

First thing, Your lambda trying to connect to localhost so this will not work. You have to place the public or private IP of the Redis instance.

But still, you need to make sure these things

  • Should in the same VPC as your EC2 instance
  • Should allow outbound traffic in the security group
  • Assign subnet
  • Your instance Allow lambda to connect with Redis in security group
const redis = require('redis');
const redis_client = redis.createClient({
    host: 'you_instance_IP',
    port: 6379
});

    exports.handler = (event, context, callback) => {
        redis_client.set("foo", "bar");

        redis_client.get("foo", function(err, reply) {
            redis_client.unref();
            callback(null, reply);
        });
    };

You can also look into this how-should-i-connect-to-a-redis-instance-from-an-aws-lambda-function

Upvotes: 1

Related Questions