Nodejs express server not closing - node.js

I have an express nodejs server with express-generator. After calling "npm start" server starts properly but I'm not able to close the connection to localhost. Typical exiting the process with "ctrl+c" doesn't work as expected. After "ctrl+c" I'm not able to start the server on the same localhost port again. I'm still using Win7, my node is up to date and other globally installed packages. My console prints out following:
$ npm start
> myapp#0.0.0 start C:\Users\Konrad\dev\myapp
> node ./bin/www
Port 3000 is already in use
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! myapp#0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the myapp#0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Konrad\AppData\Roaming\npm-cache\_logs\2018-01-19T20_02_46_983Z-debug.log
Thats the code in bin/www:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('myapp:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}

So, to avoid this issue I started using the package called "nodemon". It refreshes the code of my application without the need to restart the server.
The issue remains unsolved but I hope nobody else encounters this problem. It was probably my mistake combined with some windows7 incompatibility.

Related

Port number showing in Nodejs express folder listing

I have a node js express application which is running on port 3000. when i ran it first it worked. Then when i ran it for the second time, it says the "port is already in use". I have checked all the running ports and also searched by specific 3000 port, but still cannot find a process running on 3000 port.
Then i changed the port to 3002 and checked, now the program ran. And when i closed and ran it again, it says "port is already in use".
Same is the case when i tried with port 3003.
i tried the below to check for the running ports
sudo lsof -i -P -n | grep LISTEN
netstat -an | grep 3000
lsof -i:3000
kill <PID>
Afterwards i noticed that when i did a folder listing it showed the folder "3000", "3002", "3003" as folder/file. I don't know what this is.
below is my www file
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('mqtt-node:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3001');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
Could anyone help me with why the ran port numbers are showing in the folder listing and also i cannot find any running node ports, but still says the port is already in use.
I made a change in my env file and the issue is resolved. I had defined the port in my .env as PORT="3000" and i changed to PORT=3000, and it works.
I am not sure why PORT="3000" was working in my PC and not in my server. This is why i was not focusing on this factor.

Cannot Connect to Dockerized Express HTTPS Server

I'm trying to serve my app over HTTPS so that I can use a service worker with my React app.
To do this, I added https.createServer() to my Express startup script
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('robotapp:server');
var http = require('http');
var fs = require('fs');
var https = require('https');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '8000');
app.set('port', port);
console.log('Listening on localhost:', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Add HTTPS server
*/
if (process.env.NODE_ENV === 'prod') {
https
.createServer(
{
key: fs.readFileSync('sslcerts/server.key', 'utf8'),
cert: fs.readFileSync('sslcerts/server.pem', 'utf8')
},
app
)
.listen(443, function() {
console.log('HTTPS listening on PORT 443');
});
}
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
debug('Listening on ' + bind);
}
When I build the Docker container and start the app, both the HTTP and HTTPS server start up (I can see the "Listening on localhost:8000" and "HTTPS listening on PORT 443" messages). I can successfully access the HTTP version of my app on PORT 8000, but when I go to access PORT 443 on my server I get a "This site cannot be reached" error.
At first I thought maybe I mapped my container ports wrong, but I checked and nothing seems out of ordinary
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
16d0013eec8a robotapp:2.1 "npm start" 4 seconds ago Up 3 seconds 0.0.0.0:443->443/tcp, 0.0.0.0:8000->8000/tcp silly_tesla
If anyone has any suggestions as to what I'm doing wrong, please let me know :)

how to set local node ports for production?

Trying to bring a local project onto an ubuntu mongodb server.
Currently the project runs on my localhost:8000 when I run npm start on my server and I visit curl http://localhost:8000 i can see the markup of my homepage being outputted. How can i change this to use my domain/server ip in production?
Below is my node file which is run by npm start
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('05-express-first-app:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '8000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
My server ip address is: 165.227.196.209, just not sure where to put it.
Thanks!
You'll have to change the IP on which the Node.js server runs to be whatever the public IP address of your server is. In your case, the public IP is 165.227.196.209
This is assuming your name server is already configured to route the domain (eg: mywebsite.com) to that particular IP address.
Read more about it here - How to assign a domain name to node.js server? (Check the selected answer)
UPDATE:: Opening the URL - http://165.227.196.209/,
I notice that you're using nginx. So you'll have to setup reverse proxying.
I suggest going through the link here - Node.js + Nginx - What now?
You can read about the benefits of putting nginx infornt of Node.js here - Using Node.js only vs. using Node.js with Apache/Nginx
Couple of other problems that I notice here that would be good to fix,
You should be using a process manager to run your application in Production. Something like pm2 is recommended. This way if you application crashes, pm2 will restart it.
You can use pm2 with environment variables as described here to run on a different port on production - http://pm2.keymetrics.io/docs/usage/environment/

NodeJS app not working on Openshift after deployed

I'm having trouble with my nodejs app deployment. I use Express, MySQL and the basic Express structure for my app. When I open the app URL on openshift I get the 503 error message. On the nodejs.log, I can see this:
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
Pipe 8080 is already in use
The application is run with ./bin/www. This is the code I have in that file:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('adressbook:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
//var addr = server.address();
var addr = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
The error occurred because the OPENSHIFT_NODEJS_PORT variable was not set on your application's server. This cause the application to use the hardcoded port (8080).
To resolve this, you need to set the OPENSHIFT_NODEJS_PORT environment variable on your application's server. This can be done with:
$ rhc env set OPENSHIFT_NODEJS_PORT=<Value> -a App_Name
where <Value> is the port number you wish to use and App_Name is your application's name.
You can read more about handling environment variables on Openshift here

Fail to deploy my own nodejs to aws elastic bean stalk

I have a valid node.js app that I want to deploy to AWS EB. It is valid because it is working on my localhost by:
npm start
The zip that I upload looks like this:
My app.js looks like:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var sequelize = require('sequelize');
var routes = require('./routes/index');
var users = require('./routes/users');
var responseDTO = require('./dto/httpResponseDTO.js');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
app.use(function(err, req, res, next) {
res.status(err.status || 500);
msg = responseDTO.toReseponseDTO(false, err.name, err.errors);
res.json(msg);
});
module.exports = app;
EDIT
The package.json looks like:
{
"name" : #projectname#,
"version" : "0.1.1",
"private" : true,
"scripts" : {
"start" : "node ./bin/www"
},
"dependencies" : {
...
}
}
And the file that the script tries to run (./bin/www) looks like this:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('mee:server');
var http = require('http');
var models = require('../models');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '8081');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
It looks like this is causing problem to EB, which says:
Impaired services on all instances.
The error log says:
Server running at http://127.0.0.1:8081/
Server running at http://127.0.0.1:8081/
npm ERR! Linux 3.14.48-33.39.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v0.12.6-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v0.12.6-linux-x64/bin/npm" "start"
npm ERR! node v0.12.6
npm ERR! npm v2.11.2
npm ERR! path /var/app/current/package.json
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! enoent ENOENT, open '/var/app/current/package.json'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! Please include the following file with any support request:
npm ERR! /var/app/current/npm-debug.log
npm ERR! Linux 3.14.48-33.39.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v0.12.6-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v0.12.6-linux-x64/bin/npm" "start"
npm ERR! node v0.12.6
npm ERR! npm v2.11.2
npm ERR! path /var/app/current/package.json
npm ERR! code ENOENT
npm ERR! errno -2
It looks like the package.json isn't found? but from the folder structure it is there...
Please let me know what went wrong, it has been bothering me for a long time!
From the code you posted I cannot see the part when you actually start the server but from the logs I see that it starts in port 8081 which it is actually strange to me, I guess in EBS it must have a dynamic PORT
When you select the port you should use process.env.PORT || 8081 this will get the port set by EBS or use 8081 (in local for example).
Amazon has a good guide which should explain you how to deploy there a node app: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs_express.html
Turned out for some reason, when I remote into the linux ec2 instance used by the EB, and try node --version or sudo node --version, it says command not found. I have to manually install node and npm and manually start the server. It's weird that I have to do this though..

Resources