Search code examples
node.jsubuntu-18.04

Getting error while using cluster in Node.js


I am using cluster in node.js to create multiple workers but as per my code I am getting the following error.

Error:

Error: bind EADDRINUSE null:3000
    at listenOnMasterHandle (net.js:1420:16)
    at rr (internal/cluster/child.js:121:12)
    at Worker.send (internal/cluster/child.js:88:7)
    at process.onInternalMessage (internal/cluster/utils.js:42:8)
    at emitTwo (events.js:131:20)
    at process.emit (events.js:214:7)
    at emit (internal/child_process.js:762:12)
    at _combinedTickCallback (internal/process/next_tick.js:142:11)
    at process._tickCallback (internal/process/next_tick.js:181:9)

my server code file is given below.

app.js:

const express = require('express'),
      http    = require('http'),
      cors    = require('cors'),
      bodyParser = require('body-parser'),
      xss    = require('xss-clean'),
      helmet = require('helmet'),
      cluster = require('cluster'),
      os     = require('os'),
      mongoSanitize = require('express-mongo-sanitize');



    const app = express();
    app.use(bodyParser.json({limit:'25mb'}));
    app.use(cors());
    app.use(bodyParser.urlencoded({limit: '25mb', extended: true}));
    app.use(xss());
    app.use(mongoSanitize());
    app.use(express.static(__dirname+'/public'));
    
    
    const server = http.createServer(app);
    
    
    if(cluster.isMaster) {
        let length = os.cpus().length;
    
        for(let i = 0; i < length; i++) {
            cluster.fork();
        }
    } else {
    
        app.get('/', (req,res) => {
            res.status(200).render('index.html');
        })
    }
    
    
    server.listen('3000',() => {
        console.log('server is running ar port 3000')
    });

I am using the following command to run my server.

nodemon npm start

Here my issue is when I am implementing cluster to create multiple workers these errors are coming but without using cluster this file is running correctly. I need to resolve this error.


Solution

  • The conditional statement to your app.js needs to wrap all of your Express application functionality so, the updated file will look like this.

    else {
        const app = express();
        app.use(express.static(__dirname + '/public'));
        app.get('/', (req, res) => {
            res.status(200).render('index.html');
        });
        const server = http.createServer(app);
        server.listen('3000', () => {
            console.log('server is running ar port 3000')
        });
    }
    

    You can have a look Example link.