Node connecting to Mongodb in my VPS with port 27017, no if I change the port - node.js

I've got a Digital Ocean VPS, and followed their tutorial:
link
It's working the app.js and connecting to the database.
Here is the code of the apps file:
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
}
db.close();
});
But if I change the port 127.0.0.1:27017 to 127.0.0.1:3500 the one I want to connect, it's not working.
Here is my ufw
ufw allow 22/tcp
ufw allow 3500/tcp
ufw allow 80/tcp
ufw allow 27017/tcp
Any help?
Thank you

Man, you did a bad thing. You opened MongoDB to whole world. If your node.js app is on the same server with MongoDb, then no reasons to open 27017 & 3500 for internet. Close these ports ASAP.
Why do you think that you changed mongoDb port? Please show mongoDb config file with port configuration row. Also after you changed the mongodb config file it requires restart mongodb servic/daemon.

Related

connection error while connecting to AWS DocumentDB

getting the following error while connecting to AWS DocumentDB from node.js
connection error: { [MongoNetworkError: connection 1 to
docdb-2019-01-28-06-57-37.cluster-cqy6h2ypc0dj.us-east-1.docdb.amazonaws.com:27017
timed out] name: 'MongoNetworkError', errorLabels: [
'TransientTransactionError' ] }
here is my node js file
app.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://abhishek:abhishek#docdb-2019-01-28-06-57-37.cluster-cqy6h2ypc0dj.us-east-1.docdb.amazonaws.com:27017/?ssl_ca_certs=rds-combined-ca-bundle.pem&replicaSet=rs0', {
useNewUrlParser: true
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("connected...");
});
By default aws documentdb is designed to connect only from same VPC.
So to connect nodejs application from an ec2 in same vpc. You need to have the pem file as by default SSL is enabled while db instance is created.
step-1 : $ wget https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem in required directory
step-2 : Change the mongoose connection with options pointing to pem file
mongoose.connect(database.url, {
useNewUrlParser: true,
ssl: true,
sslValidate: false,
sslCA: fs.readFileSync('./rds-combined-ca-bundle.pem')})
.then(() => console.log('Connection to DB successful'))
.catch((err) => console.error(err,'Error'));
Here am using mongoose 5.4.0
To connnect from outside the VPC, please try to follow the below doc from aws:
https://docs.aws.amazon.com/documentdb/latest/developerguide/connect-from-outside-a-vpc.html
Personally I tried only to connect from VPC and it worked fine.
Update =====:>
To connect from Robo 3T outside VPC please follow the link -
AWS DocumentDB with Robo 3T (Robomongo)
to use AWS DocumentDB outside VPC for example your development server EC2 or from the local machine will get a connection error unless you use ssh tunneling or port forwarding
and about tunneling it simple
use this command in your local
ssh -i "ec2Access.pem" -L 27017:sample-cluster.node.us-east-1.docdb.amazonaws.com:27017 ubuntu#EC2-Host -N
in application configuration use
{
uri: 'mongodb://:#127.0.0.1:27017/Db',
useNewUrlParser: true,
useUnifiedTopology:true,
directConnection: true
}
just make sure you can connect from this tunneling ec2 and database
and if you decide to use port forwarding
steps
0- in ec2 security grou[p add inbound role with custom TCP and port 27017 All traffic
1- go to your ec2 instance and install Haproxy
$ sudo apt install haproxy
2- edit Haproxy configuration
$ sudo nano haproxy.cfg
3- in end off file add
listen mongo
bind 0.0.0.0:27017
timeout connect 10s
timeout client 1m
timeout server 1m
mode TCP
server AWSmongo <database-host-url>:27017
4- now restart HaProxy
$ sudo service HaPoxy restart
5- now you can access your database using
{uri: 'mongodb://<database-user>:<database-pass>#<EC2-IP>:27017/<db>'}

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

I'm new in nodeJS, started learning by following a trailer on youtube, everything goes well until I added the connect function if mongodb,
mongo.connect("mongodb://localhost:27017/mydb")
when I run my code on cmd (node start-app), get the following error,
MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
Could someone explain me which step I missed ?
my code :
var express = require("express");
var MongoClient = require('mongodb');
var url = "mongodb://localhost:27017/mydb";
var webService = require("./webService");
var server = express();
MongoClient.connect(url, function (err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
server.use(express.urlencoded({ extended: true }));
server.set('views', __dirname);
server.get('/', function (request, response) {
response.sendFile(__dirname + '/MainPage.html');
});
server.get('/Sign', function (request, response) {
response.render(__dirname + '/Sign.ejs');
});
server.post("/signUp", webService.signUp);
server.post("/createUser", webService.createUser);
server.listen(5500);
You have to install MongoDB database server first in your system and start it.
Use the below link to install MongoDB
https://docs.mongodb.com/manual/installation/
If you have installed MongoDB check if the server is in which state (start/stop). Try to connect through mongo shell client.
Many of them don't add this, especially in AWS EC2 Instance, I had the same issue and tried different solutions.
Solution: one of my database URL inside the code was missing this parameter 'authSource', adding this worked for me.
mongodb://myUserName:MyPassword#ElasticIP:27017/databaseName?authSource=admin
I faced same issue but after a lot of RND. I found that whts the problem so run this command on your terminal.
sudo service mongod start
then run mongo on terminal
After trying EVERY solution google came up with on stack overflow, I found what my particular problem was. I had edited my hosts file a long time ago to allow me to access my localhost from my virtualbox.
Removing this entry solved it for me, along with the correct installation of mongoDB from the link given in the above solution, and including the correct promise handling code:
mongoose.connect('mongodb://localhost/testdb').then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});
Following the logic behind #CoryM's answer above :
After trying EVERY solution google came up with on stack overflow, I found what my particular problem was. I had edited my hosts file a long time ago to allow me to access my localhost from my virtualbox.
Removing this entry solved it for me...
I had edited my hosts file too for Python Machine Learning setup 2 months ago. So instead of removing it because I still need it, I use 127.0.0.1 in place of localhost and it worked :
mongoose.connect('mongodb://127.0.0.1/testdb')
Your IP address probably changed.
If you've recently restarted your modem, this changes your IP which was probably whitelisted on Atlas.
Soooo, you'll need to jump back onto Atlas and add your new IP address to the whitelist under Security>Network Access.
This had occurred to me and I have found out that it was because of faulty internet connection. If I use the public wifi at my place, which blocks various websites for security reasons, Mongo refuses to connect. But if I were to use my own mobile data, I can connect to the database.
If the mongoDB server is already installed and if you are unable to connect from a remote host then follow the below steps,
Login to your machine, open mongodb configuration file located at /etc/mongod.conf and change the bindIp field to specific ip / 0.0.0.0 , after that restart mongodb server.
sudo vi /etc/mongod.conf
The file should contain the following kind of content:
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
storage:
journal:
enabled: true
processManagement:
fork: true
net:
bindIp: 127.0.0.1 // change here to 0.0.0.0
port: 27017
setParameter:
enableLocalhostAuthBypass: false
Once you change the bindIp, then you have to restart the mongodb, using the following command
sudo service mongod restart
Now you'll be able to connect to the mongodb server, from remote server.
I solved this problem by upgrading major version of mongoose:
Before doing this, make sure (using mongo shell) that you have the correct URL and a running mongo server is available at that URL and the problem still persists.
"dependencies": {
- "mongoose": "^5.4.13",
+ "mongoose": "^6.2.4",
}
just run mongod in terminal on the base folder if everything has been set up like installing mongo db and the client for it like mongoose. After running the command run the project file that you are working on and then the error shouldn't appear.
You can check detail of error by running this command
sudo service mongod status
if error is something like this
Failed to unlink socket file /tmp/mongodb-27017.sock Unknown error
Fatal Assertion 40486 at src/mongo/transport/transport_layer_asio.cpp 670
simply running this will resolve your issue
rm /tmp/mongodb-27017.sock
I don't know if this might be helpful, but when I did this it worked:
Command mongo in terminal.
Then I copied the URL which mongo command returns, something like
mongodb://127.0.0.1:*port*
I replaced the URL with this in my JS code.
first create folder by command line mkdir C:\data\db (This is for database)
then run command mongod --port 27018 by one command prompt(administration mode)- you can give name port number as your wish
I had this issue while working at the local Starbucks and I remembered that when I initially set up my database through Mongo Atlas. I set my IP address to be able to access the database. After looking through several threads, I changed my IP address on Atlas and the issue went away. Hope this helps someone.
This worked for me.
mongoose.Promise = global.Promise;
.connect(
"mongodb://127.0.0.1:27017/mydb",
{ useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}).then(db => {
console.log("Database connected");
}).catch(error => console.log("Could not connect to mongo db " + error));
I was using localhost, so i changed it to:
mongodb://127.0.0.1:27017/mydb
My problem was the wrong port number for mongoDB server.
I had:
DATABASE_URL= "mongodb://localhost:3000/node-express-mongodb-server"
in my .env file (my environmental variables), but I had written it before running mongoDB server. So when I ran the mongoDB server, it wrote a different port number and I had to change it. I changed it to the right port number (which was written on my cmd window by mongoDB):
DATABASE_URL= "mongodb://localhost:27017/node-express-mongodb-server"
and now it works fine.
if you are a Mac user just upgrade your homeBrew from terminal:
$ brew upgrade
$ mongod --config usr/local/etc/mongod.config
$ Xcode-select --install
$ mongo
1) If you haven't installed mongodb, install it.
2) open a new terminal, type "mongo". This is going to connect you to a MongoDB instance running on your localhost with default port 27017:
mongoose.connect('mongodb://localhost:27017/').then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});
Better just connect to the localhost Mongoose Database only and create your own collections. Don't forget to mention the port number. (Default: 27017)
For the best view, download Mongoose-compass for MongoDB UI.
This one helped me.
Try creating a new folder, if your MongoDB is installed in C:\Program Files the folder should be called db and in a folder data.
C:\data\db
When you start the mongod there should be a log where the db 'isnt found'.
So when none of the above solutions worked for me, after installing everything correctly, I thought to restart the system.
It's working now.
Note that I did everything said above, but no luck. The only restart worked for me.!!
You may also want to restart once.
You have to install MongoDB database server first in your system and start it.
Use the below link to install MongoDB
If you have already installed MongoDB database in your system then you have to check that your DB is in start position or not with the help of following steps:
press CTRL + Shift + Esc
go to the service tab and search for Mongo
check the status - it may be stopped. So click on the Services tab at the bottom right corner and again search for MongoDB
Click on it and start the DB by right click or in left panel.
If the error happens on macbook run this command to keep the mongodb server running.
mongod --config /usr/local/etc/mongod.conf --fork
The issue majorly is that your mongodb server is rejecting the connection it might be that the server is not on/active eventhough it has been installed on your macbook.
In my case the problem was that there was another instance of mongoDB server running I had shutdown my computer without stopping the server hence when I tried running mongosh it gives me that error. Try restarting the computer it will shutdown all the servers and the erro was gone.
I was trying to connect, without starting the service.
This is how i fixed the error (MacOS env).
$ brew services start mongodb-community#6.0
$ mongosh // connected to db and fixed the error.
$ brew services stop mongodb-community#6.0
For me the problem resolved when I started the MongoDB on port other than 27017. Even though nothing was running on 27017 but the problem resolved when I started it on another port.
To do that navigate to the /etc/mongod.conf and change the port: 27017 to some other port like port: 27019.
Then restart the service by:
sudo systemctl restart mongod.service.
And then try to connect to MongoDB by specifying the --port parameter like:
mongod --port 27019, or
mongo --port 27019
Best!
this was my erros:
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.2
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
SOLUTION:
The best Answes is if you using mac M1 and M2
use restrat with sudo like below
MongoNetworkError solution
sudo brew services restart mongodb-community#6.0
I connected to a VPN and the connection accomplished. I was using school's WiFi which has some restrictions apparently.
I guess you must be connecting to cloud.mongodb.com to your cluster.
One quick fix is to go to the connection tab and add your current IP address(in the cluster portal of browser or desktop app). The IP address must have changed due to a variety of reasons, such as changing the wifi.
Just try this approach, it worked for me when I got this error.
You need to initialize your mongoDB database first, you can run "mongod" in your terminal and then it will be working fine.

Can't connect Node.js to Mongodb

I'm newbie about node.js and MongoDB.
I have installed MongoDB on a server A. MongoDB is running and port 27017 is opened. I am able to connect to robo3T
I have a Node.js app on another server B. Node.js is running.
When I access the website, everything is displayed correctly but when I want to login (so it needs MongoDB access), the website turns and get this error: Cannot GET /502.shtml
Here are all details
Mongodb server
mongod.conf :
port: 27017
bindIp: 0.0.0.0
Nodejs app.js:
var promise = mongoose.connect('mongodb://XXXX:27017/preprod', {useMongoClient: true}, function(err) {
if (err) return console.error(err);});
mongoose.Promise = require('bluebird');
XXXX = address IP of server A (mongodb server)
when I run app.js I got this error
name: 'MongoError',
message: 'failed to connect to server [XXX:27017] on first connect [MongoError: connect ETIMEDOUT XXXX:27017]' }
I am able to connect from my linux machine, other VPS server but not to my nodejs server!
Maybe I missed something?
Do this on a Linux machine,
iptables -A INPUT -s 0.0.0.0 -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -d 0.0.0.0 -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT
and try connecting from the remote server (Server B) with the IP address of Server A.
Resolved:
Actually the port 27017 was closed on my nodejs server.
now it can connected!
if it can help someone else
mongoose.connect(mongodb://localhost:27017/<project_name>, {
useMongoClient: true
});
Where is the name of the project.
Make sure you've installed and imported mongoose. And also, that you've got mongod running.
Also, I'd remove 'var promise = ' before mongoose.connect(..)

RethinkDB error when connect to live server on AWS

Connecting to local server is working fine. But i have to maintain one centralized DB for my team. I setup rethinkdb on aws server and have to access this from local from each system in my local project
app.use(function(req,res,next){
r.connect({
host: '55.52.57.59',
port: 28015,
db: 'league'
},function(err,conn){
if (err) throw err;
req['app_conn']=conn;
next();
});
});
what could i do? Please help me!
Check whether you have opened 28015 port on AWS Server or not?

Having trouble setting up Postgres server to accept SSL connections

I'm on a Mac using Postgres.app to run a Postgres server.
I'm connecting to the server in Node.js (code copied from Heroku docs):
pg.defaults.ssl = true;
pg.connect(process.env.DATABASE_URL || 'postgres://localhost:5432/my-project', function(err, client) {
if (err) throw err;
console.log('Connected to postgres! Getting schemas...');
client
.query('SELECT table_schema,table_name FROM information_schema.tables;')
.on('row', function(row) {
console.log(JSON.stringify(row));
});
});
I then followed the instructions here to allow my Postgres server to accept SSL connections. I changed the ssl setting to on in my postgresql.conf file. I also generated the required files, server.key and server.crt.
However, when I run my Node server, I get this error:
Error: The server does not support SSL connections
I ran psql and did show ssl. It returned off. So then I thought that maybe I had the wrong config file...but then I did show config_file and I'm definitely in the right place. What else am I missing?
Very likely you forgot to restart the PostgreSQL server.
In case of problems, set log_connections = on and check the PostgreSQL server log.

Resources