How to tell azure to run node server.js - node.js

i have angular 6 app running fine on azure too but i need to add a server.js file for some server variables i added server.js file on root like
Server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
var router = express.Router();
const publicIp = require('public-ip');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist/projectname')));
app.get('/getip', (req, res) => {
var ipcheck = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
(async () => {
console.log(await publicIp.v4());
res.json({
ip: await publicIp.v4(),
ip2: req.headers['x-forwarded-for'],
ip3: req.connection.remoteAddress,
ip4: req.ip
});
})();
});
// Send all other requests to the Angular app
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/projectname/index.html'));
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/prjectname/index.html'));
});
//Set Port
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
then i goto cmd and run node server.js it works great on localhost
but now i want to do same on azure server how to deploy it.
or how to tell azure always run node server.js

I assume that you have known how to create an Azure WebApp in Azure Portal or Azure CLI. Then, I see you developed your Node.js app in Visual Stodio 2017 and want to deploy it to Azure using the same tool, so I suggested you can refer to the NTVS wiki page Publish to Azure Website using Web Deploy to know how to do.
Next, there are four notes below you have to know first before deploying.
Please confirm the Node.js version in your created WebApp, the default version is 0.10+. You can accessing the Kudo console of your webapp via the url https://<your webapp name>.scm.azurewebsites.net/DebugConsole and command node -v to get it. You can set it in Azure CLI to run the command like az webapp config appsettings set --resource-group <your ResourceGroup> --name <app_name> --settings WEBSITE_NODE_DEFAULT_VERSION=10.14.1 or follow the figure below in Azure portal. For more details about Node version on Azure WebApp, please refer to my answer for the SO thread azure webapp webjob node version.
In your project, there must be a Web.config file to talk with IIS on Azure WebApp how to startup your Node app. The content of Web.config file is the same as the sample in the Kudu wiki page Using a custom web.config for Node apps, you can directly copy it because your bootstrap js file name also is server.js.
The listening port on Azure WebApp is random assigned by environment, you can get it from the environment variable HTTP_PLATFORM_PORT which also will be got by process.env.PORT. So you will not do anything in your code for port.
Your Node app will be deployed into the path home/site/wwwroot of Azure WebApp which also can be accessed via Kudu console. Therefore, without any tools, you also can use Kudu console to deploy your app, just make the file structure in wwwroot as same as your project, which includes all js files and directories, node_modules and web.config.

just build your project ng build --prod then open project folder in dist folder in vs 17 then add
package.json
index.js
web.config
you can get these 3 files form here and you can edit index.js as per need i just need to add this
app.get('/getip', (req, res) => {
res.json({
ip: req.headers['x-forwarded-for'].split(":")[0]
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
this runs my app through nodejs.
when i call getip this gives me server ip and otherwise return angular index.html which handle all routing.

Related

Azure Deployment Failure - Container didn't respond to HTTP pings on port: 8080, failing site start

I am deploying a web application that uses NodeJS, Express and React on Azure App Service (plugged to my BitBucket repo), and I'm not finding success. Either the deployment fails, or it claims it is successful, but the site is unaccessible and keeps timing out. When I check the Docker logs in my Azure diagnosis, I notice the following:
2021-02-14T13:41:53.578Z INFO - Initiating warmup request to container mcm-app_0_543ad0c3 for site mcm-app
And after several logs that read Waiting for response to warmup request for container mcm-app_0_543ad0c3, I get the following:
2021-02-14T13:45:44.205Z ERROR - Container mcm-app_0_543ad0c3 for site mcm-app did not start within expected time limit. Elapsed time = 230.6269687 sec
2021-02-14T13:45:44.236Z ERROR - Container mcm-app_0_543ad0c3 didn't respond to HTTP pings on port: 8080, failing site start. See container logs for debugging.
2021-02-14T13:45:44.299Z INFO - Stopping site mcm-app because it failed during startup.
This is what my server.js file for the Express backend looks like:
var express = require("express");
var cors = require("cors");
var app = express();
var path = require("path");
const port = process.env.PORT || 8080;
// Enable CORS and handle JSON requests
app.use(cors());
app.use(express.json());
app.post("/", function (req, res, next) {
// console.log(req.body);
res.json({ msg: "This is CORS-enabled for all origins!" });
});
// Set router for email notifications
const mailRouter = require("./routers/mail");
const readerRouter = require("./routers/reader");
const notificationsRouter = require("./routers/booking-notifications");
app.use("/email", mailRouter);
app.use("/reader", readerRouter);
app.use("/notifications", notificationsRouter);
app.use(express.static("./mcm-app/build"));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "mcm-app", "build", "index.html"));
});
app.listen(port, () => {
// console.log(`Server is running on port: ${port}`);
});
My client's package.json does not contain any proxy command, by the way. I removed it. The error appears with/without it anyway.
Also, per some recommendations, I've tried setting WEBSITES_PORT to 8080 in my Azure configurations. But nothing works so far.
I'd appreciate it if I could get some detailed guidance to resolve this. I'm not using a .yml file, in case that helps.
I found Isaac has managed to resolve this issue with below solution.
Adding tty: true for it in docker-compose.yml file. Also, to make the frontend-backend interaction work as expected in the app, changing proxy command in client's package.json to the following:
"proxy": "http://backend:5000"
And changing links command in docker-compose.yml to this:
- "backend:be"
Sharing the answer here to help others who may encounter the same issue in the future.

How to deploy NextJS application to Linux Server (CentOS 7) - VPS

I've got a question regarding building applications. I'm using simple VPS with node.js support. Now I do not know how to build my next.js application to production.
I want to deploy my application as static files.
I thought that I should use next build && next export then copy out dir to the server but during this process, I faced some issues - when I change route - everything is okay, but if I refresh the page - the page is not found because the server is looking for this file in directories. So how can I deploy my nextjs application in production mode with VPS server and static files?
I tried one thing which is not working fine probably or I did something wrong.
I added nodejs express server with
const express = require('express');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({dev});
const router = express.Router();
const handle = app.getRequestHandler();
app.prepare()
.then(() => {
const server = express();
server.get('*', (req, res) => {
return handle(req, res);
});
server.listen(3000, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
});
and start server with forever library NODE_ENV=production node server.js and it's working fine, but seems this is working in a wrong way - seems it's normal server like in dev mode - so it shouldn't be like that. (I see thunder icon on the right-bottom corner and I see all files which are same as in dev mode).
I want to deploy everything as static files.
Thank you for your help!
After you build and export you need to serve those files somehow. The reason the Express server works is because you are starting a HTTP server to serve the files.
So you need to serve those files either by using a static hosting provider (i.e. Vercel or Amazon S3). Otherwise you should start a server on your linux machine using something like serve to serve it at a port, similar to your Express server serving it as localhost:3000 which is then exposed on your VPS.

Improper Routing when deploying Node.js app to Render VPS

I am deploying a Node.js Express app to a VPS by Render. When I run the app on my local machine, the npm start command does a great job of serving my file when I point the browser to localhost:3001. However, after I deploy, the base directory '/' returns "Not found". I have to point my browser to example.onrender.com/public/index.html.
How do I make sure that example.onrender.com/ routes the request to public/index.html?
Thank you!
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
res.render('index.html');
});
app.listen(3001);
Actually just had to change "Publish Directory" settings in Render to ./public

Deploying first app to Heroku: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

I am trying to deploy an Express/React/Mongo app to Heroku for the first time.
It is failing with a 503 error. The logs states the following:
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within
60 seconds of launch
I have set the following port variable in the root index.js file:
const port = process.env.PORT || 3000;
and use it here:
app.listen(port, function(){
console.log("Express server is running on port " + port)
})
It outputs "Express server is running on port 3000", which suggest that it is not picking up the Environmental variable.
I have been trying to follow instructions here: https://coursework.vschool.io/deploying-mern-with-heroku/
The key part that I am may be misunderstanding:
With Heroku, you need to set the environment variables on your newly
created Heroku app so it knows which values to use when the project is
deployed. You can do this two ways, either online on Heroku's website,
or through the command line using the heroku CLI. Since we are not
creating a new Heroku remote repository, all environment variables
will need to be added using Heroku.com.
I took this to mean that I should set an environmental variable Heroku.com, which I believe I have done so:
What am I failing to grok?
EDIT: I have tried setting theprocess.env.PORT=8000 from the Heroku CLI:
heroku config:set process.env.PORT=8000
But get the following error:
» Error: Missing required flag: » -a, --app APP app to run
command against » See more help with --help
Here is the full index.js:
const express = require('express'),
cors = require('cors'),
app = express(),
port = process.env.PORT || 3000;
bodyParser = require('body-parser'),
todoRoutes = require('./routes/todo'),
path = require("path");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.use(express.static(path.join(__dirname, "client", "build")))
app.get('/', function (req, res){
res.send('Root route')
})
app.use('/api/todos', todoRoutes);
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
app.listen(port, function(){
console.log("Express server is running on port " + port)
})
I had local dev server running whilst deploying to Heroku. Tried redeploying after stopping dev server, and it worked. Local servers interfered with environment variables in deployment.

Node.js app 404 errors for public directory in Google App Engine Flexible production environment

I've been working with the Node.js Google App Engine for some months and have always successfully used the express.static solution to access static files in the public folder when i deployed my node.js app.
For some (to me not so obvious) reason I struggle to get this working lately in the Google Flexible production environment. On my local development environment everything is fine.
In order to narrow down the problem I created a very basic test app listed here:
'use strict'
const express = require('express')
const app = express()
const path = require('path')
const os = require('os')
const PORT = process.env.PORT || 8080
const ENV = process.env.NODE_ENV
//app.use(express.static('public'))
//app.use(express.static(path.resolve(__dirname, 'public')))
app.use(express.static(path.join(__dirname, 'public')))
app.listen(PORT, () => {
console.log(`SYSTEM: App listening on port ${PORT}`)
console.log(`SYSTEM: Press Ctrl+C to quit.`)
})
app.get('/', (req,res) => {
res.status(200).send('\
<h1>TEST app.use(express.static("public")) in Google Cloud Flexibel App Engine environment </h1>\
<hr/>\
<h4>YAML settings: runtime: nodejs env: flex</h4>\
<h4>HOST : '+`${os.hostname()}`+'</h4>\
<h4>PORT : '+`${PORT}`+'</h4>\
<h4>__dirname : '+`${__dirname}`+'</h4>\
<h4>mountpath : '+`${app.mountpath}`+'</h4>\
<h4>env : '+`${ENV}`+'</h4>\
<h4>path resolved: '+`${path.resolve(__dirname, 'public')}`+'</h4>\
<h4>path joined : '+`${path.join(__dirname, 'public')}`+'</h4>\
<hr/>\
<h2>If you see me <img src="./HB.png"> you can access "./HB.png" in the "public" directory.</h2>\
<h2>If you see me <img src="/HB.png"> you can access "/HB.png" in the "public" directory.</h2>\
<h2>If you see me <img src="HB.png"> you can access "HB.png" in the "public" directory.</h2>\
<hr/>\
')
})
I tried various settings of the express.static settings (see those commented out). However each time after deploying using
gcloud app deploy
to Google production I get 404 (also in the google logs). On local development environment everything is fine.
Does anyone have a clue ? Thanks in advance !
Strange, I solved it by reinstalling the Google Cloud SDK.

Resources