Reputation: 829
I've created my first app with MEAN stack (Mongo, Express, Angular 2/4, Node) but it only works on "local enviorment" I am starting client (front end) part by ng serve and it’s works on localhost:4200
Also I am starting server part by node server.js and it works on localhost:4000
Also starting mongodb.
All works perfect but on localhost.
How can I deploy app to production on my own server I don’t want any hosting like heroku etc.
I have installed debian + mongo and node.
This is my server.js file
require('rootpath')();
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// use JWT auth to secure the api
app.use(expressJwt({ secret: config.secret }).unless({ path: ['/users/authenticate', '/users/register'] }));
// routes
app.use('/users', require('./controllers/users.controller'));
// start server
var port = process.env.NODE_ENV === 'production' ? 80 : 4000;
var server = app.listen(port, function () {
console.log('Server listening on port ' + port);
});
config.json
{
"connectionString": "mongodb://localhost:27017/mymean",
"apiUrl": "http://localhost:4000",
"secret": "TOP SECRET"
}
How can I start it on my own machine?
Upvotes: 0
Views: 828
Reputation: 10177
As for the front-end, if you still want any dev-features you can use
ng serve --host=somedomain/ip --port=80
to bind to whatever ip/port you want (0.0.0.0 should also work). If you just want the files then you should use use ng build
or ng build --environment="production"
. (The latter triggers some extra optimizations from webpack.) Building your app will generate a dist
-folder (by default anyway) and the contents are simple html/javascript files, so you need to serve that folder by some other means (nginx perhaps).
I use nginx to make my api (server-side) publicly available as well. A nginx config can be as simple as:
server {
listen 80;
# Web
root /var/www/myapp/dist
location / {
try_files $uri /index.html;
}
# Api
location /api {
proxy_pass http://127.0.0.1:4000;
}
}
Also, many uses something to keep the server process alive. Instead of just NODE_ENV=production node server.js
, there are tools like nodemon, forever or pm2. I'm biased towards pm2, but it's all very subjective. Those process managers are very handy if you run your server on some VPS. Probably less so if you run it on your own machine. (node server.js
is fine too).
Upvotes: 1