0

I am having a NodeJS application with some basic routes and sql server connectivity. I am using pkg for the executables. All the configuration settings are stored on .env file. When I am trying to run multiple instance of the application from different directories with different port number specified in the .env file, my app is crashing with "EADDRINUSE" error code and says the particular port is used. I am able to run only single instance of application with any defined port number in .env file. I didn't explicitly use any default port number in the application.

"use strict";
const express = require("express");
const mac = require("./auth/auth");
const ejs = require("ejs");
var log = require('./utils/scroll');
var bodyParser = require("body-parser");
const app = express();
app.use(require('./utils/init'));
app.use(bodyParser.urlencoded({ extended: true, limit: "500mb"}));
app.use(bodyParser.json({limit: "500mb"}));
app.use(require('./utils/cors'));
app.use('/',require('./routes'));

console.log(mac);
var port = (process.env.port);
log();
app.use("/", express.static("assets"));
app.set("view engine", "ejs");
app.listen(port,()=>{
console.log("Server Running at Port :", port);  
});

Is there any other setting I have to do?.

I had tried configuring different .env files with different port numbers per application.

MGUCE
  • 1
  • 2

1 Answers1

0

The port your express app will be using is the one defined by process.env.port which I assume comes for your .env file.

You need handle the case the port is already in use to automatically change the port number and try again.

Something like that:

const express = require("express");

const app = express();
app.portNumber = 3000;

function listen(port) {
    app.portNumber = port;
    app.listen(port, () => {
        console.log("server is running on port :" + app.portNumber);
    }).on('error', (err) => {
        if(err.code === 'EADDRINUSE') {
            console.log(`----- Port ${port} is busy, trying with port ${port + 1} -----`);
            listen(port + 1)
        } else {
            throw err;
        }
    });
}

listen(app.portNumber);

Check this post for a more complete answer: https://stackoverflow.com/a/53110778/5103610

Almaju
  • 1,283
  • 12
  • 31