Hosting NodeJS (Express and Angular) Project on Ub

2019-07-25 18:22发布

问题:

I have a domain and a cloud server (running ubuntu 16.04 OS) and I trying to host a nodeJS project (with ExpressJS and AngularJS) on cloud server.

I have currently installed node, nginx on my cloud server. My app is currently running on localhost even on server.

This is my node server.js file I'm having.

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.set('port', (process.env.PORT || 3000));
app.use(express.static(__dirname + '/app'));
app.set('views', __dirname + '/app');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(bodyParser.urlencoded({
   extended: true
}));
app.use(bodyParser.json());


app.get('*', function(req, res){
    res.render('index.html');
});

app.listen(app.get('port'), function() {
});

console.log('Magic happens on port ' + app.get('port'));

Can someone help me by giving me detailed steps on how to host my nodejs project on cloud server with nginx.

My project directory structure is as follows

-project_directory_name
  |-app(folder_where_my_html_css_javascript_code_is_placed)
  |-node_modules
  |-package.json(file)
  |-server.js (node/express file)

I have placed my project_directory_name under the root (/) directory in my server.

Thank you in advance.

回答1:

Step of deployment:

  1. clone your code on any desired location.
  2. install npm and bower(if you have).
  3. install forever sudo npm install forever --global
  4. forever start server.js

Above will help you to start service of your node application.now your node app run.

Hosting nginx: Node.js + Nginx - What now?

 location / {
    proxy_pass http://127.0.0.1:3000/;
    proxy_read_timeout 120s;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

add this to nginx config file. just simple run your node app

Hope this may help you!