Unable to connect to remote redis host [nodeJS] - node.js

const redis = require('redis');
require('dotenv').config();
console.log(process.env.redisHost, ':', process.env.redisPort);
const redisClient = redis.createClient({
host: process.env.redisHost,
port: process.env.redisPort,
password: process.env.redisKey
});
redisClient.connect();
redisClient.on('error', err => console.log('Redis error: ', err.message));
redisClient.on('connect', () => console.log('Connected to redis server'));
module.exports = redisClient;
I tried this sample from redis docs but still I'm getting an error stating:
Redis error: connect ECONNREFUSED 127.0.0.1:6379
I logged the environment host and port variables to the console and I got the remote host ipv4 address, but still the client is trying to connect to localhost instead of remote host (I purposely uninstalled redis from my local device to check if the client is working as it is supposed to). I also confirmed that the remote redis host is working perfectly.
I also tried different methods like :
https://cloud.google.com/community/tutorials/nodejs-redis-on-appengine
redis.createClient(port, host, {auth_pass: password});
But still, I got the same error.
I am able to connect to the redis host via commandline:
redis-cli.exe -h XX.XX.XX.XXX -a Password
XX.XX.XX.XXX:6379> set name dhruv
OK
XX.XX.XX.XXX:6379> get name
"dhruv"
XX.XX.XX.XXX:6379> exit
I'm trying to use redis on nodejs for the first time, so don't have a proper idea but I think I am doing everything right.
Any solution/workaround will be helpful :D

It worked with this code:
const url = `redis://${process.env.redisHost}:${process.env.redisPort}`;
const redisClient = redis.createClient({
url,
password: process.env.redisKey
});
redisClient.connect();

can you check if in the destination the port is reachable. it maybe the firewall block your access

Related

redis is working in local but not working in server

I have a redis server which is working fine in my local but in ubuntu server is not working can someone gives the comment for installing redis in server
it is not working even with docker it is working only while i am running in local
const redis=require('redis');
var redisClient:any;
(async () => {
try {
redisClient = redis.createClient({ socket: { port: 6379 } });
await redisClient.connect();
// const redisClient = redis.createClient({
// port:"6379",
// host:'redis-service'
// });
redisClient.on('connect',()=>{
console.log('server connected to redis')
})
redisClient.on('ready',()=>{
console.log('Client Connect to redis and ready to use')
})
redisClient.on('error',(err:any)=>{
console.log(err)
})
redisClient.on('end',()=>{
console.log('Server disconnected from redis')
})
process.on('SIGINT',()=>{
redisClient.quit()
})
console.log('connected');
} catch (err) {
console.error(err)
}
})()
export{
redisClient
};
Make sure that Redis is not already running on the server. You can check this by running the command ps aux | grep redis. If Redis is running, you should see a line with the redis-server process.
Confirm that Redis is properly installed on your server by running redis-cli ping. If Redis is installed and running, it should return "PONG"
Check the Redis configuration file (redis.conf) and ensure that the IP and port settings match the settings on your local machine.
Make sure that the Redis server has the necessary permissions to access its data directory and that the correct ownership and permissions are set on its files.
Verify that the firewall rules on the server allow incoming connections on the Redis port (usually 6379)
Check for any compatibility issues between the version of Redis that you're running on your local machine and the version of Redis that's running on the Ubuntu server. If there's a version mismatch, it may be necessary to upgrade or downgrade one of the installations.
Try to run the Redis server with verbose output by running the command redis-server -v, this can give you some more information about the errors that are causing the server to fail.
Look at Redis log files, usually located in /var/log/redis for further clues about the cause of the problem.

Connecting to azure flexible postgres server via node pg

I am using the free subscription at Azure and have successfully created a Ubuntu Server and a Flexible Postgres Database.
Until recently I accessed the DB directly from my Windows 10 desktop. Now I want to route all access through the Ubuntu Server.
For this I have installed Open SSH Client and Open SSH Server on my Windows 10 machine and done the necessary local port forwarding with ssh -L 12345:[DB IP]:5432 my_user#[Ubuntu IP]
The connection works, I confirmed it with pgcli on my desktop with pgcli -h 127.0.0.1 -p 12345 -u my_user -d my_db
But when I am trying to connect via node-pg I receive the following error
UnhandledPromiseRejectionWarning: error: no pg_hba.conf entry for host "[Ubuntu IP]", user "my_user", database "my_db", SSL off
I have already added a Firewall Rule in Azure with the [Ubuntu IP], and the error remains. What bugs me further is that in the Azure Portal of the DB I have enabled "Allow public access from any Azure service within Azure to this server", so the extra Firewall should not even be necessary for this connection.
For the last week, I have been stuck on this and now the connection is finally established, but not accessible by my code. Pretty frustrating. I would be glad about ANY pointers on how to fix this.
Edit #1:
I can't post the pg_hba.conf file. Because the Postgres DB is managed by Azure, I do not have access to pg_hba, which makes the situation more difficult to understand.
My node.js code for testing the connection:
const pg = require("pg");
const passwd = "...";
const client = new pg.Client({
user: 'admin',
host: '127.0.0.1',
database: 'test',
password: passwd,
port: 12345
});
client.connect()
client.on('uncaughtException', function (err) {
console.error(err.stack);
});
const query = "SELECT * FROM test";
try {client.query(query, (err,res) => {
if (err) {
console.error(err);
}
console.log(res);
})}
catch (e) {
console.error(e)
}
The comment by #jjanes helped me in understanding the issue, thank you.
This edited pg.Client config solved my problem:
const client = new pg.Client({
user: 'admin',
host: '127.0.0.1',
database: 'test',
password: passwd,
port: 12345,
ssl: {rejectUnauthorized: false}
});
I found this specific SSL option here https://node-postgres.com/features/ssl

Local mongodb Node.js server succesfully authenticates then ends connections after a few seconds

I am trying to run an Express server that would communicate with a local MongoDB instance. Everything runs on Ubuntu 18.04.5 on DigitalOcean.
I managed to set up the database, the authentication is made, but then after a few seconds the connection closes due to some mongodb dependencies (I think).
This is how I make the connection:
const httpsServer = https.createServer(credentials, app);
const mongooseConnection = mongoose
.createConnection(
`mongodb://user:pass#127.0.0.1:27017/Database?retryWrites=true&w=majority`,
{ useNewUrlParser: true, useUnifiedTopology: true }
);
mongooseConnection.on('error', console.error.bind(console, 'Connection error: '));
mongooseConnection.once('open', () => {
console.log("Connected to the DB");
httpsServer.listen(securePort, () => {
console.log(`Secure Express server listening on port ${securePort}`);
});
});
Node console:
Mongod:
Couldn't find much about this error. Most of what I've found is related to the MongoDB Atlas cloud service, but this is a local MongoDB instance. The common solution for when the connection closes like this seems to be whitelisting the IP. I think this is not the case as everything is local and I have nothing to do with the Atlas/Cluster.
I tried removing the node modules and updating them. I tried disabling cors and helmet. I'm stuck

Can redis client work without a redis datastore installed?

In my node web server, I am using a the npm module redis.
when I run my code...
const client = redis.createClient();
client.on("error", function (err) {
console.log("Error " + err);
});
client.hmset(["key", "test keys 1", "test val 1", "test keys 2", "test val 2"], function (err, res) {});
I get an error:
Error Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
I don't have a redis database installed. Do I need that?
If not, anything I have missed in my code?
Yes, you need to install Redis and ensure the server is running. This is a link to the official page for downloading the redis.
In your application code, you need to ensure you are connecting to Redis server with the right port and host address. By default, Redis server should be running on 127.0.0.1:6379 and that is where redis.createClient would try to connect to by default. If your Redis server is running on another port or host, then you need to specify those details when connecting e.g:
redis.createClient({
host: '<the host where redis is running>',
port: '<the port where redis is running>'
});
You can check here for more info on the options you can provide when connecting to Redis server with redis.createClient.

Can't Connect To A Telnet Server From Node.js

I have a telnet server embedded in a C++ app that I can connect to with no problem
using telnet.
I want to write a node application that will connect to my server and I have tried
this
var net = require('net');
var port = 6502
var host = '127.0.0.1'
var socket = net.connect(port,host, function() {
console.log("Sending data");
socket.write("hello\r\n")
socket.on("data", function (data) {
console.log("received data");
console.log( data.toString() );
socket.end();
})
})
socket.on("error", function(err) {
console.log("Error");
console.log(err);
})
Unfortunately what I get back is this
> node test.js
{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }
What's really odd is if I set up a simple echo server with node everything works
fine. Here's the working echo server code:
var net = require('net');
var server = net.createServer(function (socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(6502, '127.0.0.1');
and from that I get
Sending data
received data
Echo server
hello
Is there any reason why:
I can telnet into my app fine
I can connect from node to my node echo server on the same port
I get a connection refused if I connect from my node app to my app
Extra Info
On OSX (mavericks)
Node version 0.10.28
Telnet server in C++ is provided via embedded lua and luasocket (lua 5.1)
Solved!
The issue is the code in my app server was binding to localhost and by default
that binds to the IPV6 address of ::1
Passing a host of localhost to net.connect assumes IPV4 and doesn't work.
The mac command line telnet and nc both work fine with this and connect correctly.
Two solutions:
App binds to 127.0.0.1 and localhost in node works fine
Set host address to ::1 in test.js and it connects via ipv6
All fixed now though :)
gaz
Looks like you forgot to tell the server to listen in your code. It throws a connection refused error because there is nothing to connect to...
Add this at the end: server.listen(port);
The prototype for net.connect is (options, callback)
See http://nodejs.org/api/net.html#net_net_connect_options_connectionlistener
I would then suggest to test your code against a standard telnet server to see how it behaves, and finally I would strongly recommend the use of jshint or jslint.

Resources