Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple servers on Node.js

I need to simulate four servers (with different host and port) on the same nodejs instance.

An example could be:

domain1:8000 - domain2:8010 - domain3:8020 - domain4:8030 -

Can anybody please help me? Thanks

like image 942
McKenzie Avatar asked Jul 31 '18 18:07

McKenzie


2 Answers

const express = require("express");

const server1 = express();
const server2 = express();
const server3 = express();

server1.listen(8000, () => {
    console.log("Server 1 is up and running on port 8000");
})

server2.listen(8010, () => {
    console.log("Server 2 is up and running on port 8010");
})

server3.listen(8020, () => {
    console.log("Server 3 is up and running on port 8020");
})

express() creates and returns an instance of a server. call it multiple times to create multiple instances. listen on different ports. that's all.

like image 30
Aniket Kariya Avatar answered Sep 20 '22 03:09

Aniket Kariya


I add an example with a possible solution for 2 servers using node.

First, you need to create a project:

mkdir simulate4servers
cd simulate4servers
npm init (entry point: index.js)

Install Express:

npm install express --save

Put the next files into the directory:

File app.js:

'use strict';
const express = require('express');
const app = express();
const routes = require('routes.js');

app.use('/',routes);

module.exports = app;

File app2.js:

'use strict';

const express = require('express');
const app2 = express();
const routes = require('routes2.js');

app2.use('/',routes);

module.exports = app2;

File configDomain1.js:

module.exports = {
    port: 8000
}

File configDomain2.js:

module.exports = {
    port: 8010
}

File routes.js:

'use strict';

const express = require('express');
const api = express.Router();

api.get('/', (req,res)=>{
  res.send({message: 'Hello World!'});
});
module.exports = api;

File routes2.js:

'use strict';

const express = require('express');
const api = express.Router();

api.get('/', (req,res)=>{
  res.send({message: 'Hello World 2!'});
});
module.exports = api;

File index.js:

'use strict';

const app = require('./app')
const app2 = require('./app2')
const config = require('./configDomain1');
const config2 = require('./configDomain2');

app.listen(config.port, () => {
    console.log(`API REST running in http://localhost:${config.port}`);
});

app2.listen(config2.port, () => {
    console.log(`API REST running in http://localhost:${config2.port}`);
});

And finally, run it:

node index.js
like image 111
fernandezbcn Avatar answered Sep 21 '22 03:09

fernandezbcn