I am programming in Express.js, running within an AWS Elastic Beanstalk instance, trying to connect to an AWS ElastiCache instance with Redis. I get this error:
web: Error connecting to Redis Error: connect ECONNREFUSED 127.0.0.1:6379
web: at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
web: errno: -111,
web: code: 'ECONNREFUSED',
web: syscall: 'connect',
web: address: '127.0.0.1',
web: port: 6379
web: }
What is interesting is that I can PING Redis within the same program (and I get back a PONG), but I cannot connect using "createClient".
Here is the relevant code:
import * as dotenv from "dotenv";
dotenv.config();
import express from "express";
import { createClient } from "redis";
import net from "net";
const app = express();
console.log("NOTE: Pre createClient");
console.log("*** HOST = ", process.env.REDIS_HOST);
console.log("*** PORT = ", process.env.REDIS_PORT);
//----------------------------------------
// Pinging Redis Server
//----------------------------------------
const client = new net.Socket();
client.setTimeout(5000);
client.connect(process.env.REDIS_PORT, process.env.REDIS_HOST, () => {
client.write("PING\r\n");
});
client.on("data", (data) => {
console.log("PING TEST: Reply: ", data.toString());
client.destroy();
});
client.on("error", (err) => {
console.error("PING TEST: Error connecting to Redis server:", err);
client.destroy();
});
client.on("timeout", () => {
console.error("PING TEST: Connection timed out.");
client.destroy();
});
//----------------------------------------
// Connecting to Redis
//----------------------------------------
let redisClient = createClient({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT || 6379,
});
redisClient.on("connect", () => {
console.log("Connected to Redis");
});
redisClient.on("error", (error) => {
console.error("Error connecting to Redis", error);
});
console.log("NOTE: Pre connect");
console.log("*** redisClient = ", JSON.stringify(redisClient));
try {
await redisClient.connect();
} catch (error) {
console.error("Error connecting to Redis CLIENT:", err);
}
console.log("NOTE: Post connect");
Above the error listed above, I get this output
web:> *<name-of-app>*@1.0.0 start
web: > node index.js
web: NOTE: Pre createClient
web: *** HOST = aia-elasti-redis.*<6 digits>*.clustercfg.euw1.cache.amazonaws.com
web: *** PORT = 6379
web: NOTE: Pre connect
web: *** redisClient = {"_events":{},"_eventsCount":2,"bf":{},"cms":{},"cf":{},"tDigest":{},"topK":{},"graph":{},"json":{},"ft":{},"ts":{}}
web: PING TEST: Reply: +PONG
Because I get back the "PONG", I know that: (a) the Redis Server is running, and (b) I can reach it from the Elastic Beanstalk server using the AWS Configuration Endpoint.
There is no username or password set up. So, I cannot think of any other way to format the createClient
I find it odd that I do not see the "NOTE: Post connect" even though the redisClient.connect() is within a try/ catch.