how to connect MongoDB in Cloud9? - node.js

I have a problem with the connection database MongoDB in Cloud9
Please help to resolve this issue!
var MongoClient = require("mongodb").MongoClient;
var port = process.env.PORT;
var ip = process.env.IP;
MongoClient.connect("mongodb://"+ip+":"+port+"/test",function(error,db){
if(!error){
console.log("We are connected");
}
else{
console.dir(error); //failed to connect to [127.4.68.129:8080]
}
});
Output:
Running Node Process
Your code is running at 'http://demo-project.alfared1991.c9.io'.
Important: use 'process.env.PORT' as the port and 'process.env.IP' as the host in your scripts!
[Error: failed to connect to [127.4.68.129:8080]]

If you follow https://docs.c9.io/setting_up_mongodb.html this link, you will setup and run your mongodb daemon under your workspace.
And if you take a look at the output of ./mongod, you'll find out this output:
2015-08-22T12:46:47.120+0000 [initandlisten] MongoDB starting : pid=7699 port=27017 dbpath=data 64-bit host=velvetdeth-express-example-1804858
Just copy the host and port value to your mongodb config, set up the database url, in this case is:
mongodb://velvetdeth-express-example-1804858:27017

process.env.PORT and process.env.IP are the port and IP address for your application, not your database. You'll want to pull your Mongo connection string from your MongoDB provider.
Below is the hello world example from the Node.js homepage modified to use the two environment variables.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(process.env.PORT || 1337, process.env.IP || '127.0.0.1');

For anyone else who runs into this issue, the solution is here: https://docs.c9.io/setting_up_mongodb.html
MongoDB is preinstalled in the Cloud9 workspace. Run this:
$ mkdir data
$ echo 'mongod --bind_ip=$IP --dbpath=data --nojournal --rest "$#"' > mongod
$ chmod a+x mongod
To start the Mongodb process, run:
$ ./mongod
Then 'run' your node.js app script and you're off to the races.
Here's what the parameters mean:
--dbpath=data (because it defaults to /var/db which isn't accessible)
--nojournal because mongodb usually pre-allocates 2 GB journal file (which exceeds Cloud9 disk space quota)
--bind_ip=$IP (because you can't bind to 0.0.0.0)
--rest runs on default port 28017

Related

What can be the reason why i get an Nodejs Error EPERM: 3000?

I'm deploying my node.js ts application on ubuntu server
app.js file listening to port 3000
var port = 3000
app
.use(authRoutes_1.default.routes())
.use(keysRoutes_1.default.routes())
.use(exchangesRoutes_1.default.routes())
.use(wishlistRoutes_1.default.routes())
.listen(port, function () {
console.log('Listening on port ' + port);
});
When i approach my domen through browser i get an error listen eperm 3000
Then i created another one simple server listener js file with the following code
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!');
});
server.listen(3000);
And suprisingly it works perfectly well
Another funny thing that running both files from ubuntu using node app.js throws the same EPERM error
How to solve this puzzle?
It seems like port 3000 is already used by another process. Can you try something like sudo lsof -i -P -n | grep LISTEN to check if there is any other process using that port ? Or can you try change to another port to see if your node server works ?

Can't communicate with simple Docker Node.js web app [duplicate]

This question already has answers here:
Containerized Node server inaccessible with server.listen(port, '127.0.0.1')
(2 answers)
Closed 9 months ago.
I'm just trying to learn Node.js and Docker at the same time. I have a very simple Node.js app that listens on a port and returns a string. The Node app itself runs fine when running locally. I'm now trying to get it running in a Docker container but I can't seem to reach it.
Here's my Node app:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
var count = 0;
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end("Here's the current value: " + count);
console.log('Got a request: ', req.url);
count++;
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
My Dockerfile:
FROM node:latest
MAINTAINER Jason
ENV PORT=3000
COPY . /var/www
WORKDIR /var/www
EXPOSE $PORT
ENTRYPOINT ["node", "app.js"]
My build command:
docker build -t jason/node .
And my run command:
docker run -p 3000:3000 jason/node
The app.js file and Dockerfile live in the same directory where I'm running the commands. Doing a docker ps shows the app running but I just get a site cannot be reached error when navigating to 127.0.0.1:3000 in the browser. I've also confirmed that app.js was properly added to the image and I get the message "Server running at http://127.0.0.1:3000/" after running.
I think I'm missing something really simple, any ideas?
Omit hostname or use '0.0.0.0' on listen function. Make it server.listen(port, '0.0.0.0', () => { console.log(Server running..); });
If You use docker on Windows 7/8 you most probably have a docker-machine running then You would need to access it on something like 192.168.99.100 or whatever ip your docker-machine has.
To see if you are running a docker-machine just issue the command
docker-machine ls

connect ECONNREFUSED 127.0.0.1:27017'

I have that code:
var express = require('express'),
stylus = require('stylus'),
logger = require('morgan'),
bodyParser = require('body-parser'),
mongoose = require('mongoose');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
function compile(str, path){
return stylus(str).set('filename', path);
}
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(stylus.middleware(
{
src: __dirname + '/public',
compile: compile
}
));
app.use(express.static(__dirname + '/public'));
mongoose.connect('mongodb://localhost/multivision');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error..'));
db.once('open', function callback(){
console.log('multivision db opened');
});
app.get('/partials/:partialPath', function(req, res){
res.render('partials/' + req.params.partialPath);
});
app.get('*', function(req, res) {
res.render('index');
});
var port = 3131;
app.listen(port);
console.log('Listening on port ' + port + '...');
but when I'm trying nodemon server.js it throws an error:
connection error.. { [MongoError: connect ECONNREFUSED
127.0.0.1:27017] name: 'MongoError' message: 'connect ECONNREFUSED 127.0.0.1:27017' }
how can I improve that? I've already installed mongoose using npm install mongoose --save in my directory
Yeah there are dozens question like this but none of these helped me.. I'm new at nodejs and probably missing something
I was also facing the same issue, when I was executing node server on my project directory. For me the MongoDB service was not started, that makes this issue.
So I had to run services.msc and activated the service.
After that I was able to run my command.
D:\SVenu\MyApp>node server
Saving User
App is listening on port: 3000
Already Exist
Already Exist
Already Exist
Already Exist
Done save
run services.msc and activate the Mongodb service.
Now Mongodb will connect
the status of the Mongodb indicated as Running
Your mongodb service is probably down.
Run sudo service mongod start to start the daemon process
I was having the same problem, and found that it was a mongod issue.(I am running Ubuntu 16.04). Looking through the errors there was a directory missing. After adding the directory, I needed to change permissions, and finally, set the mongod service to start at boot.
$ sudo mkdir -p /data/db
$ sudo chown -R $USER /data/db
$ sudo systemctl enable mongod.service
I know this issue is old, but i came across a similar issue and the above solutions did not work for me, I'm using Ubuntu 20.04 LTS.
What i did to make it work was just running mongo service using this command:
$ mongod
Then everything worked fine
If you're in windows and you had this issue,
just go the installer exe app for the mongodb
and click "Repair"
this works for me
try this:
mongod.exe --dbpath c:\data\db
c:\data\db is the place where you put your db.
and when you see something like this :
2016-08-18T10:22:31.020+0800 I CONTROL [main] Hotfix KB2731284 or later update is not installed, will zero-out data files
2016-08-18T10:22:31.022+0800 I CONTROL [initandlisten] MongoDB starting : pid=4356 port=27017 dbpath=c:\data\db 64-bit host=sevencai-PC0
2016-08-18T10:22:31.022+0800 I CONTROL [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2016-08-18T10:22:31.023+0800 I CONTROL [initandlisten] db version v3.2.8
2016-08-18T10:22:31.023+0800 I CONTROL [initandlisten] git version: ed70e33130c977bda0024c125b56d159573dbaf0
......
and then node yourserver.js
maybe everything will be fine!
Follow as below:
=> run services.msc and start mondodb server
and save the file in node project, you can see the server connected!!
In Most of the case you will get the error bcz the service MongoDB Database Server (MongoDB) Might be stopped.
Just start the service to be connected with DB
it's doesn't work as localhost but IP address works 127.0.0.1 and solves this problem:
// .connect("mongodb://localhost:27017/lofydb")
const mongoose = require("mongoose");
mongoose.connect("mongodb://127.0.0.1:27017/lofydb")
// .connect("mongodb://127.0.0.1:27017")
.then(() => {
console.log("Connected to Database");
})
.catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});
please check the MongoDB service is active and running.
Refer the running services
If it is running and available on MongoDB compass or on MongoDB shell and if you are working with node version >17.0.0 or so it will give error.
So plz change to the stable version of node.
Make sure MongdoDB is running
To run MongoDB as a macOS service, run:
brew services start mongodb-community#5.0
And when you see:
==> Successfully started mongodb-community (label:
homebrew.mxcl.mongodb-commu
OR type on command line, to check the mongo service.
mongod
After run service, You can easily connect with mongdoDB localhost or remote connection.
I had the same issue and it had to do with the fact that my MongoDB service wasn't running locally. Make sure you followed all the correct installation steps for whatever OS you are trying to run MongoDB service here: https://www.mongodb.com/docs/manual/administration/install-community/
Then follow the respective guide for the running the service under "Run MongoDB Community Edition". So for example, for macOS you would do
brew services start mongodb-community#6.0
if you wanted to run as a macOS service, or
mongod --config /opt/homebrew/etc/mongod.conf --fork
if you wanted to run manually as a background service on Apple M1 processor. The same page I shared above also has commands you can run for verifying if your MongoDB process is running.
Step 1: open conf file to edit.
sudo vim /etc/mongod.conf
Step 2: find port and change it.
net: port: 27017 -> default port before any change
After changing port, my issue solved :

Bridged Adapter Issue Windows 10 VB 5.0.12 Ubuntu 14.04

I'm learning Node.js and I've installed VirtualBox and there ubuntu server 14.04. Node.js is installed as well on ubuntu. I'm doing an exercise in which I created a server which is accessible from guest_localhost:3000 (in ubuntu). The thing is I've not installed any GUI (and I wish to continue in that way). I want to test that the server I created using Node.js is running. To do that I just need to go to server_localhost:3000.
Apparently everything is ok (for example ping host to guest ip), but for some reason it´s not working.
ping ok __ not working
`var http = require('http');
var handleRequest = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Welcome to Node Essential Training\n');
};
var server = http.createServer(handleRequest);
server.listen(3000, 'localhost');`
I'll appreciate any help.
Thanks in advance guys.
If you do not have any GUI to visibly verify your page layout, you should be able to access it from your windows machine if they are in the same local network by simply accessing the url http://your_ubuntu_local_ip:3000 where your_ubuntu_local_ip is the local ip your ubuntu machine has internally in your local network. You can find this ip by typing ifconfig in your ubuntu terminal and looking for the ip the network adapter you are using has.
It's solved. The problem was in the code to create the server after all. As I'm learning JavaScript and Node.js I'm watching a tutorial in Lynda.com. The code which doesn't work comes from Lynda. The other from this url: http://blog.modulus.io/build-your-first-http-server-in-nodejs
// THIS CODE DOES NOT WORK
//var http = require('http');
//
//var handleRequest = function (req, res) {
// res.writeHead(200, {'Content-Type': 'text/plain'});
// res.end('Welcome to Node Essential Training\n');
//};
//
//var server = http.createServer(handleRequest);
//
//server.listen(8080, 'localhost');
//THIS CODE WORKS
//Lets require/import the HTTP module
var http = require('http');
//Lets define a port we want to listen to
const PORT=3000;
//We need a function which handles requests and send response
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});

Say 'Hello World!' in Openshift with Node.js

I created an app in Openshift and created a local git repo on my computer. I want to change the default welcome page here: http://nodejs-j4nos.rhcloud.com:3000 and just tell Hello world as this tutorial say.
So I removed from local repo the index.html, and modified server.js, pasted in this code below. And commit, and push. I get a long approval, that they accepted my commit.
If I good understand I do not have to stop node and start it again, but Openshift do it for me. But as you can see no Hello World is able to see, when open link in browser (http://nodejs-j4nos.rhcloud.com:3000) why?
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
remote: Git Post-Receive Result: success
remote: Activation status: success
remote: Deployment completed with status: success
To ssh://5556b4c4fcf9336abf0000de#nodejs-j4nos.rhcloud.com/~/git/nodejs.git/
and here is the tree structure, express is listed
Based on this SO answer I tried to modify script, but does not helped:
var express = require('express');
var app = express();
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 8080);
app.set('ip', process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1');
http.createServer(app).listen(app.get('port'), app.get('ip'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
Link is working now: http://nodejs-j4nos.rhcloud.com The right script to show "Hello world!" is
var http = require('http');
var express = require('express');
var app = express();
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 8080);
app.set('ip', process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1');
http.createServer(app).listen(app.get('port'), app.get('ip'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
And here is the proof:
Thanks for this: Deployed Node app to OpenShift successfully, OpenShift still shows default page
and this question: Node.js Deployment in openshift
And you should now that you can write in /app-root/repo the $ node server.js command, and if something wrong with script, it will indicate right there
I´ve readed this, maybe you must use a port over 15000:
https://help.openshift.com/hc/en-us/articles/202185874-I-can-t-bind-to-a-port
Found my notes on using OpenShift with Node:
The openshift system has some integrated control tools to support its ‘gear’ system, useful to control the openshift
application and environment.
gear control your application (start, stop, restart, etc)
or deps with --cart (gear start --cart mysql-5.1)
tail_all tail all log files. This command displays the last entries
in your log files as they are written. You can hit
<ctrl>-c to exit this command.
export list available environment variables
rm remove files / directories
ls list files / directories
ps list running applications
kill kill running applications
mysql interactive MySQL shell
mongo interactive MongoDB shell
psql interactive PostgreSQL shell
quota list disk usage
The gear system has additional commands. OpenShift Gear Control, An assortment of gear utilities:
COMMANDS:
build Run the build steps
deploy Run the deploy steps
help Display global or [command] help documentation.
postreceive Run the git postreceive steps
prereceive Run the git prereceive steps
reload Reload a cart
remotedeploy Run the remotedeploy steps
restart Restart a cart
restore Restore an application
snapshot Snapshot an application
start Start the gear/cart
status Get the status for a cart
stop Stop the gear/cart
Will any of this stuff help you stop and restart the gear? I'd start with the simple 'gear' command. I don't remember, is Express loaded up via NPM or now native with node? At one time it was a NPM install. Those don't get pushed to Openshift.
What is the directory tree structure on the openshift nodejs server?
root
\ app-root
\ data
\ repo <- - the working files for web content end up here.
\ runtime
\ git
\ nodejs
In openshift dependencies don't get pushed. For that you can login thru ssh and go to:
cd app-root/repo or cd $OPENSHIFT_REPO_DIR and then npm install tool_of_choice

Resources