amazon-web-serviceslambdaredislocalhosteconnrefused

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.


Solution

  • 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

    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