optimus
optimus

Reputation: 729

Run Multiple node application in same port ec2

I'm from java background, i started using node js and im loving it now. I have read the other threads similar to my questions before im posting it in SO.

I have 3 different node application(app 1, app2, app3) Usually if its in java i will deploy three apps in tomcat and can access them locally like this localhost:8080/app1, localhost:8080/app2 etc. Im looking for similar approach in node js. I have read this thread and installed express globally and made a script called master.js with this code

var express = require('express'); var app = express();

app .use('/app1', require('./app1/server.js').app) .use('/app2', require('./app2/server.js').app) .listen(8080);

but im getting

TypeError: Cannot read property 'handle' of undefined

Since im new to node, im not sure is this process is complicated like setting proxy etc as mentioned in this thread

basically im looking for deploying all my apps in same port and access them like localhost:8080/app1, localhost:8080/app2

do i need nginx and proxy to achieve this ?

Also in ec2 instance i can run my node app by going into app1 folder and typing node server.js so the app will be listing in port 8080 but when i press ctrl c to do other task, it terminated the app.

Upvotes: 2

Views: 2180

Answers (2)

user1695032
user1695032

Reputation: 1142

You don't need nginx/proxy to handle this. From what i can see your code should work if your app1|app2/server.js-s are built like this:

var express = require('express');
var app = express();

app.get('/hello', function() {...})

module.exports = {
    app: app
}

now you can send GET requests to /app1/hello and /app2/hello

Upvotes: 1

DiegoRBaquero
DiegoRBaquero

Reputation: 1274

You need to use a variable for each app and then use it. Try:

var app1 = require('./app1/server.js').app
var app2 = require('./app2/server.js').app
app.use('/app1', app1).use('/app2', app2).listen(8080);

Upvotes: 1

Related Questions