I know my question is repeated. Please read the question completely before marking as duplicate or anything.
I am learning node.js to create rest api & doing great on it.Everything was going smooth till i found this error( EADDRINUSE) on restart the app. This issue eat my precious hours but still not able to find the correct fix.
If the application is running for the 1st time, it launch's smoothly with out any port change for some reason we stop or restart the app this error message while be thrown from the server. Many of them suggested just change the port everything work smooth and I do agree with them.But When server is live & used worldwide you can't change the port to restart.
Adding Snippet of my Code.
app.js
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var config = require('./Config/config.js');
var api = require('./apis/api');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
app.all('/api/write/'+config.WRITE_API_VERSION+'/:apiName', function (req, res) {
api.handle.apply(null, ['write', req.method.toLowerCase(), req.params.apiName, req, res]);
console.log("in api end1"+req.body);
});
app.all('/api/read/'+config.READ_API_VERSION+'/:apiName', function (req, res) {
api.handle.apply(null, ['read', req.method.toLowerCase(), req.params.apiName, req, res]);
console.log("in api end2");
});
app.use(function (req, res, next) {
res.contentType('application/json');
next();
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(config.PORT);
console.log('Magic happens on port ' + config.PORT);
config.js
var configs = {
ENVIRONMENT: "development",
READ_API_VERSION: "v1.0",
WRITE_API_VERSION: "v1.0",
PORT: 8080
}
Object.freeze(configs);
module.exports = configs;
Package.json
"scripts": {
"start": "node app.js"
}
Error Message
node app.js
Magic happens on port 8080
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1039:14)
at listen (net.js:1061:10)
at Server.listen (net.js:1135:5)
at EventEmitter.listen (/home/ubuntu/vcare_backend/VCare/node_modules/express/lib/application.js:617:24)
at Object.<anonymous> (/home/ubuntu/vcare_backend/VCare/app.js:47:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
After running the command sudo netstat -plnt
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 3277/node
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1073/sshd
tcp6 0 0 :::22 :::* LISTEN 1073/sshd
Your issue is that node is already running on port 8080. This is shown by the first line returned by the netstat/lsof command. Killing the process will allow you to restart the node process. You can do this on a mac by using the command
killall node
Where node is the name of the process.
Node is already running on your machine.
In Terminal, find the running Node process with
ps -ax | grep node
This will return a list of the running node processes. The first column in the resulting list of processes is the process id (pid).
Kill the running node process with
kill -9 <pid>
This will kill the node process and free up the port for you to run your server.
Related
My nodejs app is crashing in Heroku. I have two server running in two different ports. One for express routes and another for socket.io. Apps builds fine and deployed in Heroku. It starts, DB connection is OK, then a server daemon also works fine for some period. Then it change state to crashed. No error log after the crash and no reason for crash. Here is log from Heroku,
2020-04-22T14:52:19.980682+00:00 app[web.1]: > iLearn#1.0.0 start /app
2020-04-22T14:52:19.980683+00:00 app[web.1]: > PORT=5000 node server.js
2020-04-22T14:52:19.980683+00:00 app[web.1]:
2020-04-22T14:52:20.741515+00:00 app[web.1]:
2020-04-22T14:52:20.782048+00:00 app[web.1]: API server started on: 5000
2020-04-22T14:52:21.087402+00:00 app[web.1]: Messaging Manager started..
2020-04-22T14:52:21.087501+00:00 app[web.1]: MessagingManager::startDaemon
2020-04-22T14:52:21.089358+00:00 app[web.1]: Messaging server running on port:5001
2020-04-22T14:52:21.130079+00:00 app[web.1]: DB Connected
2020-04-22T14:52:21.132905+00:00 app[web.1]: {"timestamp":"2020-04-22T14:52:21.131Z","message":"DB Connected","level":"info"}
2020-04-22T14:52:26.097164+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:52:31.100561+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:52:36.107406+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:52:41.112479+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:52:46.116481+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:52:51.121785+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:52:56.127394+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:53:01.136499+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:53:06.136680+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:53:11.144029+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:53:16.145616+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:53:16.792389+00:00 heroku[web.1]: State changed from starting to crashed
Here is my server.js file,
const express = require('express')
const MessagingManager = require("./util/messagingManager")
app = express()
bodyParser = require('body-parser');
require('dotenv').config();
port = process.env.PORT || 5000;
app.listen(port);
console.log('API server started on: ' + port);
app.use(express.static('public'))
//app.use(formidable());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('view engine', 'pug');
app.set('views', './views')
var routes = require('./routes'); //importing route
app.use('/', routes); //register the route
const messagingApp = express();
const messagingServer = require("http").createServer(messagingApp);
const io = require("socket.io").listen(messagingServer);
let messagingManager = new MessagingManager()
messagingManager.startDaemon()
port = process.env.MESSAGING_PORT || 5001;
io.on("connection", socket => {
console.log("a user connected");
let id = socket.handshake.query.id
console.log(socket.id)
messagingManager.addConnection(id, socket)
socket.on("message", msg => {
if (msg.type == "MESSAGE_READ_STATUS")
messagingManager.setMessageStatus(msg)
else
messagingManager.sendMessage(msg)
});
socket.on("disconnect", () => {
//io.emit("chat message", msg);
});
socket.on("endsession", msg => {
//io.emit("chat message", msg);
console.log("session ended." + id)
messagingManager.removeConnection(msg.id)
socket.disconnect()
});
// not used
socket.on("session", msg => {
//io.emit("chat message", msg);
console.log("session established")
messagingManager.addConnection(msg.id, socket)
});
});
messagingServer.listen(port, () => console.log("Messaging server running on port:" + port));
It's hard to actually to know why the application crashed as log just says, application crashed without any message. Port binding error was not thrown and app listen callback function is called. Actual issue seems to be port. I have set port in both .env and package.json file. It overrides heroku dynamic port. Thanks #Beppe C to pointing out this. I deleted port variable from both .env and package.json and redeploy the app. Now it is working fine. Another issue is heroku app does not allow two port in the same application. So, I have to create two app. One for express HTTP route and another for socket.io. Hope it helps someone.
I am having a very strange crash in nodejs, the error is
Error: listen EADDRINUSE :::3000
at Object.exports._errnoException (util.js:1020:11)
at exports._exceptionWithHostPort (util.js:1043:20)
at Server._listen2 (net.js:1258:14)
at listen (net.js:1294:10)
at Server.listen (net.js:1390:5)
at Object.<anonymous> (C:\Users\tyler\Desktop\workspace\stream pop-up\index.js:18:6)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
and my code is
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require("fs");
var port = process.env.PORT || 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/popup.html');
});
fs.watchFile("assets/popup.json", {interval:100}, function(curr, prev)
{
console.log("working")//dosen't go here
fs.readFile("assets/popup.json",{encoding:"utf8"}, function(err, data){
io.emit("popup", data)
})
});
http.listen(port, function()
{
console.log("working")//doesn't go here
console.log('listening on *:' + port);
});
console.log("working") //this one prints
the exact same code was working a before, the only difference was I put this file, along with the node_modues in a subfolder, and then took them out of that subfolder, because I was getting the same error. I have no idea why this is happening, and any help would be appreciated
edit: I now know that the problem is the port is in use, but I don't know why. I tried using a python script subprocess.Popen t call this script, but it errored out after the next line of code was ran (the creation of a tkinter window)
The port 3000 is already in use, you could try to change port 3000 to some other port or kill the instance running in the port 3000.
on mac and linux
killall node
on windows
taskkill /f /im node.exe
Your port 3000 already in use. Try to change port 3000 or kill the script running in this port.
If you are using Linux or Unix, try to run this command to verify port is in use:
sudo lsof -i -P -n | grep LISTEN
Or in Windows:
netstat -a -b
I'm trying to run a basic node.js file on an aws server running ubuntu 14.04 and apache 2.4.7
var http = require('http');
var hostname = '33.33.33.33';
var port = 3000;
var server = http.createServer(function(req, res) {
console.log(req.headers);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello World</h1>');
});
server.listen(port, hostname, function() {
console.log('Server running at http://${hostname}:${port}/');
});
The hostname is just the IP to the server. Should it be something else? Should the hostname be the IP or should it be something else?
The above code gives the following error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRNOTAVAIL
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1020:19)
at listen (net.js:1061:10)
at net.js:1135:9
at dns.js:72:18
at process._tickCallback (node.js:415:13)
at Function.Module.runMain (module.js:499:11)
at startup (node.js:119:16)
at node.js:901:3
********Update*********
I have updated my code with localhost. That got rid of the error and allowed me to run the .js file. However I can't access the file from the server. I type in the IP like so
**.**.**.**:3000
This returns the message:
This site can’t be reached
**.**.**.** refused to connect.
ERR_CONNECTION_REFUSED
I also try accessing the location the file is located on the server but I get the same result.
**.**.**.**:3000/nodelearning/c1_node_week1/node-express
After I run:
node myNodeApp.js
In the terminal, I just need to access the IP of the server from a web browser right? Do I need to access only the root **.**.**.**:3000 or do I need to access the specific location of the node file **.**.**.**:3000/learningNode/myNodeApp.js
I only need to access the root right?
So **.**.**.**:3000 should work?
Below is the .js file that I'm able to run. But I can't access.
var express = require('express'),
http = require('http');
var hostname = 'localhost';
var port = 3000;
var app = express();
app.use(function (req,res, next) {
console.log(req.headers);
res.writeHead(200, {'Content-Type': 'text/html' });
res.end('<html><body><h1>Hello World</h1></body></html>');
});
var server = http.createServer(app);
server.listen(port, hostname, function(){
console.log('Server running at http:// NVM');
});
Cheers
the issue is with
var hostname = '33.33.33.33';
because when routes are recycled new ip address are assigned to the machine. so this will fail. As a recomendation skip host parameter in listen() or if you still want to use hostname use
var hostname = '127.0.0.1';
or
var hostname = 'localhost';
hope it helps :)
I try to run my Express server on ports 80 and 443, but I'm getting an error that they are already being used.
EADDRINUSE err
However, my Ubuntu server says that in fact ports 80 and 443 aren't busy:
ubuntu#ip-182-47-78-432:~$ sudo netstat -nlp
I get:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 4549/node
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1102/sshd
tcp 0 0 0.0.0.0:27000 0.0.0.0:* LISTEN 14651/mongod
tcp 0 0 0.0.0.0:8090 0.0.0.0:* LISTEN 4549/node
tcp 0 0 127.0.0.1:27017 0.0.0.0:* LISTEN 12374/mongod
tcp6 0 0 :::22 :::* LISTEN 1102/sshd
udp 0 0 0.0.0.0:68 0.0.0.0:* 580/dhclient
udp 0 0 0.0.0.0:23728 0.0.0.0:* 580/dhclient
udp6 0 0 :::1742 :::* 580/dhclient
Active UNIX domain sockets (only servers)
Proto RefCnt Flags Type State I-Node PID/Program name Path
unix 2 [ ACC ] STREAM LISTENING 8966 1104/acpid /var/run/acpid.socket
unix 2 [ ACC ] SEQPACKET LISTENING 7449 412/systemd-udevd /run/udev/control
unix 2 [ ACC ] STREAM LISTENING 8521 869/dbus-daemon /var/run/dbus/system_bus_socket
unix 2 [ ACC ] STREAM LISTENING 7430879 14651/mongod /tmp/mongodb-27000.sock
unix 2 [ ACC ] STREAM LISTENING 1636971 1/init #/com/ubuntu/upstart
unix 2 [ ACC ] STREAM LISTENING 19618017 20335/node /home/ubuntu/.forever/sock/worker.1429234248700JdV.sock
unix 2 [ ACC ] STREAM LISTENING 8616395 12374/mongod /tmp/mongodb-27017.sock
unix 2 [ ACC ] STREAM LISTENING 19620699 21172/node /home/ubuntu/.forever/sock/worker.1429234407027ZZT.sock
What can be happening? Or what other command can I run to find something useful?
Edit 1:
My code:
var fs = require('fs');
var http = require('http');
var https = require('https');
var app = require('./app');
var credentials = {
key: fs.readFileSync('private_key.pem', 'utf8'),
cert: fs.readFileSync('com_certificate.pem', 'utf8'),
ca: [
fs.readFileSync('com_certificate_chain_1.pem', 'utf8'),
fs.readFileSync('com_certificate_chain_2.pem', 'utf8')
]
};
http.createServer(app).listen(80, function() {
console.log('HTTP server started on port ' + 80 + '...');
});
https.createServer(credentials, app).listen(443, function() {
console.log('HTTPS server started on port ' + 443 + '...');
});
Edit 2:
I'm on an Amazon cloud server, it doesn't have a Skype running.
Edit 3:
var express = require('express');
var app = module.exports = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var methodOverride = require('method-override');
var cors = require('cors');
var corsOptions = require('./config/cors');
var config = require('./config/db');
var spreadsheet = require('./services/spreadsheet');
// models
var User = require('./app/models/user.js');
var Goal = require('./app/models/goal.js');
var Portfolio = require('./app/models/portfolio.js');
var Security = require('./app/models/security.js');
// environment variables
app.set('views', __dirname + '/app/views');
app.set('view engine', 'ejs');
// configure db
app.set('/api/v1', config.db[app.settings.env]);
mongoose.connect(app.get('/api/v1'), function(err) {
if(err) { return console.error(err); }
});
// mongoose.connection.on('error', console.error.bind(console, 'Connection error: '));
mongoose.connection.once('open', function cb() {
console.log('Connected.');
console.log(app.settings.env);
});
// get data from a POST request
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// get data from cookies
app.use(cookieParser());
// make PUT and DELETE requests from views
app.use(methodOverride(function(req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
var method = req.body._method;
delete req.body._method;
return method;
}
}));
// enable pre-flight and cors for every route
app.options('*', cors());
app.use(cors(corsOptions));
// force HTTPS redirect
app.use(function(req, res, next) {
if (!req.secure) {
return res.redirect('https://' + req.get('host') + req.url);
}
next();
});
// api routes
var user_routes = require('./routes/user_routes');
var security_routes = require('./routes/security_routes');
var portfolio_routes = require('./routes/portfolio_routes');
var goal_routes = require('./routes/goal_routes');
app.use('/api/v1/users', user_routes);
app.use('/api/v1/securities', security_routes);
app.use('/api/v1/portfolios', portfolio_routes);
app.use('/api/v1/goals', goal_routes);
// MVC routes
var user_controller = require('./app/controllers/user_controller');
var security_controller = require('./app/controllers/security_controller');
var portfolio_controller = require('./app/controllers/portfolio_controller');
var goal_controller = require('./app/controllers/goal_controller');
app.use('/users', user_controller);
app.use('/securities', security_controller);
app.use('/portfolios', portfolio_controller);
app.use('/goals', goal_controller);
Edit 4:
The error message I get when trying to run the server:
ubuntu#ip-172-31-15-213:~/services/api$ nodemon server.js
17 Apr 21:12:17 - [nodemon] v1.3.7
17 Apr 21:12:17 - [nodemon] to restart at any time, enter `rs`
17 Apr 21:12:17 - [nodemon] watching: *.*
17 Apr 21:12:17 - [nodemon] starting `node server.js`
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EACCES
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1023:19)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at Object.<anonymous> (/home/ubuntu/services/api/server.js:17:24)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
17 Apr 21:12:17 - [nodemon] app crashed - waiting for file changes before starting...
Looks like I got a different error this time though...
Edit 5:
If I run telnet localhost 80, I get:
ubuntu#ip-172-31-15-213:~/services/api$ telnet localhost 80
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
Your error says Error: listen EACCES, not EADDRINUSE.
The reason for the EACCES is that binding to ports below 1024 (like 80 and 443) requires root privileges, and you don't seem to be starting your app as root (before doing that, please make sure you know the implications of running apps as the root user).
If you are using skype
try disabling it to use port 80 for connections
Open Skype if it has not already been launched
Go to Tools –> Options from the dropdown menu
Select “Advanced” in the left-hand column, last option
Select “Connection”
Deselect the option that says, “Use port 80 and 443 as alternatives for incoming connections”
Click Save
Exit and then restart Skype
here is the link
I have been trying to fix this for hours, with endless googling, I try to start the app, go to the url and see a 503 Service Unavailable error, I then cd into app-root/repo, try to manually start server.js, and get the following:
[my-app-url.rhcloud.com repo]\> node server.js
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
Connecting to server
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1039:14)
at listen (net.js:1061:10)
at net.js:1143:9
at dns.js:72:18
at process._tickCallback (node.js:415:13)
at Function.Module.runMain (module.js:499:11)
at startup (node.js:119:16)
at node.js:902:3
This is driving me insane, all I'm trying to do is a simple api, and it works perfectly in my local environment.
Thank you.
Already another program or instance of this program is running on same port.
run - sudo netstat -tapen | grep ":<<your given port>>"
and then kill the process.
Then try to run the server...
Thanks
You need to bind to the OPENSHIFT_NODEJS_IP, i see you are only binding to the correct port, not the ip also: https://developers.openshift.com/en/node-js-getting-started.html
https://github.com/openshift-quickstart/openshift-nodejs-http-and-websocket-example/blob/master/server.js#L1
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var WebSocketServer = require('ws').Server
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write("Welcome to Node.js on OpenShift!\n\n");
response.end("Thanks for visiting us! \n");
});
server.listen( port, ipaddress, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
wss = new WebSocketServer({
server: server,
autoAcceptConnections: false
});
wss.on('connection', function(ws) {
console.log("New connection");
ws.on('message', function(message) {
ws.send("Received: " + message);
});
ws.send('Welcome!');
});
console.log("Listening to " + ipaddress + ":" + port + "...");