Struggling to upload my node.js application to azure - node.js

I am a beginner at node.js and need to host an application that I didn't personally write on an azure server for some testing. The site runs fine locally hosted, as well as hosted using ngrok. Yet, when I host it on azure, I get the following error:
[1] 2020-08-23T00:26:36
Container etuition_0_41152ef3 didn't respond to HTTP pings on port: 8080, failing site start
[2] 2020-08-23T00:26:36
Container etuition_0_41152ef3 for site etuition did not start within expected time limit.
Now I must stress that I am completely unfamiliar with node.js, but to me it seems that the http requests are lining up correctly. Here is the code for my index.js, where I think the problem may lie.
'use strict';
/**
* Load Twilio configuration from .env config file - the following environment
* variables should be set:
* process.env.TWILIO_ACCOUNT_SID
* process.env.TWILIO_API_KEY
* process.env.TWILIO_API_SECRET
*/
require('dotenv').load();
const express = require('express');
const http = require('https');
const path = require('path');
const { jwt: { AccessToken } } = require('twilio');
const VideoGrant = AccessToken.VideoGrant;
// Max. period that a Participant is allowed to be in a Room (currently 14400 seconds or 4 hours)
const MAX_ALLOWED_SESSION_DURATION = 14400;
// Create Express webapp.
const app = express();
// Set up the paths for the examples.
[
'bandwidthconstraints',
'codecpreferences',
'dominantspeaker',
'localvideofilter',
'localvideosnapshot',
'mediadevices',
'networkquality',
'reconnection',
'screenshare',
'localmediacontrols',
'remotereconnection',
'datatracks',
].forEach(example => {
const examplePath = path.join(__dirname, `../examples/${example}/public`);
app.use(`/${example}`, express.static(examplePath));
});
// Set up the path for the quickstart.
const quickstartPath = path.join(__dirname, '../quickstart/public');
app.use('/quickstart', express.static(quickstartPath));
// Set up the path for the examples page.
const examplesPath = path.join(__dirname, '../examples');
app.use('/examples', express.static(examplesPath));
/**
* Default to the Quick Start application.
*/
app.get('/', (request, response) => {
response.redirect('/quickstart');
});
/**
* Generate an Access Token for a chat application user - it generates a random
* username for the client requesting a token, and takes a device ID as a query
* parameter.
*/
app.get('/token', function(request, response) {
const { identity } = request.query;
// Create an access token which we will sign and return to the client,
// containing the grant we just created.
const token = new AccessToken(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_API_KEY,
process.env.TWILIO_API_SECRET,
{ ttl: MAX_ALLOWED_SESSION_DURATION }
);
// Assign the generated identity to the token.
token.identity = identity;
// Grant the access token Twilio Video capabilities.
const grant = new VideoGrant();
token.addGrant(grant);
// Serialize the token to a JWT string.
response.send(token.toJwt());
});
// Create http server and run it.
const server = http.createServer(app);
const port = process.env.PORT || 8080;
server.listen(port, function() {
console.log('Express server running on *:' + port);
});
Here is my package.json
{
"name": "video-quickstart-js",
"version": "1.0.0-dev",
"description": "Twilio Video SDK Quick Start for JavaScript",
"main": "index.js",
"scripts": {
"build": "npm-run-all build:* ",
"build:examples": "npm-run-all build:examples:*",
"build:examples:bandwidthconstraints": "copyfiles -f examples/bandwidthconstraints/src/helpers.js examples/bandwidthconstraints/public && browserify examples/bandwidthconstraints/src/index.js > examples/bandwidthconstraints/public/index.js",
"build:examples:codecpreferences": "copyfiles -f examples/codecpreferences/src/helpers.js examples/codecpreferences/public && browserify examples/codecpreferences/src/index.js > examples/codecpreferences/public/index.js",
"build:examples:dominantspeaker": "copyfiles -f examples/dominantspeaker/src/helpers.js examples/dominantspeaker/public && browserify examples/dominantspeaker/src/index.js > examples/dominantspeaker/public/index.js",
"build:examples:localvideofilter": "copyfiles -f examples/localvideofilter/src/helpers.js examples/localvideofilter/public && browserify examples/localvideofilter/src/index.js > examples/localvideofilter/public/index.js",
"build:examples:localvideosnapshot": "copyfiles -f examples/localvideosnapshot/src/helpers.js examples/localvideosnapshot/public && browserify examples/localvideosnapshot/src/index.js > examples/localvideosnapshot/public/index.js",
"build:examples:mediadevices": "copyfiles -f examples/mediadevices/src/helpers.js examples/mediadevices/public && browserify examples/mediadevices/src/index.js > examples/mediadevices/public/index.js",
"build:examples:networkquality": "copyfiles -f examples/networkquality/src/helpers.js examples/networkquality/public && browserify examples/networkquality/src/index.js > examples/networkquality/public/index.js",
"build:examples:reconnection": "copyfiles -f examples/reconnection/src/helpers.js examples/reconnection/public && browserify examples/reconnection/src/index.js > examples/reconnection/public/index.js",
"build:examples:screenshare": "copyfiles -f examples/screenshare/src/helpers.js examples/screenshare/public && browserify examples/screenshare/src/index.js > examples/screenshare/public/index.js",
"build:examples:localmediacontrols": "copyfiles -f examples/localmediacontrols/src/helpers.js examples/localmediacontrols/public && browserify examples/localmediacontrols/src/index.js > examples/localmediacontrols/public/index.js",
"build:examples:remotereconnection": "copyfiles -f examples/remotereconnection/src/helpers.js examples/remotereconnection/public && browserify examples/remotereconnection/src/index.js > examples/remotereconnection/public/index.js",
"build:examples:datatracks": "copyfiles -f examples/datatracks/src/helpers.js examples/datatracks/public && browserify examples/datatracks/src/index.js > examples/datatracks/public/index.js",
"build:quickstart": "browserify quickstart/src/index.js > quickstart/public/index.js",
"clean": "npm-run-all clean:*",
"clean:examples": "npm-run-all clean:examples:*",
"clean:examples:bandwidthconstraints": "rimraf examples/bandwidthconstraints/public/index.js examples/bandwidthconstraints/public/helpers.js",
"clean:examples:codecpreferences": "rimraf examples/codecpreferences/public/index.js examples/codecpreferences/public/helpers.js",
"clean:examples:dominantspeaker": "rimraf examples/dominantspeaker/public/index.js examples/dominantspeaker/public/helpers.js",
"clean:examples:localvideofilter": "rimraf examples/localvideofilter/public/index.js examples/localvideofilter/public/helpers.js",
"clean:examples:localvideosnapshot": "rimraf examples/localvideosnapshot/public/index.js examples/localvideosnapshot/public/helpers.js",
"clean:examples:mediadevices": "rimraf examples/mediadevices/public/index.js examples/mediadevices/public/helpers.js",
"clean:examples:networkquality": "rimraf examples/networkquality/public/index.js examples/networkquality/public/helpers.js",
"clean:examples:reconnection": "rimraf examples/reconnection/public/index.js examples/reconnection/public/helpers.js",
"clean:examples:screenshare": "rimraf examples/screenshare/public/index.js examples/screenshare/public/helpers.js",
"clean:examples:localmediacontrols": "rimraf examples/localmediacontrols/public/index.js examples/localmediacontrols/public/helpers.js",
"clean:examples:remotereconnection": "rimraf examples/remotereconnection/public/index.js examples/remotereconnection/public/helpers.js",
"clean:examples:datatracks": "rimraf examples/datatracks/public/index.js examples/datatracks/public/helpers.js",
"clean:quickstart": "rimraf quickstart/public/index.js",
"start": "npm run clean && npm run build && node server"
},
"repository": {
"type": "git",
"url": "git+https://github.com/twilio/video-quickstart-js.git"
},
"keywords": [
"twilio",
"video",
"chat",
"ip",
"real",
"time",
"diggity"
],
"author": "Twilio",
"license": "MIT",
"bugs": {
"url": "https://github.com/twilio/video-quickstart-js/issues"
},
"homepage": "https://github.com/twilio/video-quickstart-js#readme",
"dependencies": {
"dotenv": "^4.0.0",
"express": "^4.15.2",
"prismjs": "^1.6.0",
"stackblur-canvas": "^1.4.0",
"twilio": "^3.19.1",
"twilio-video": "^2.7.0"
},
"devDependencies": {
"browserify": "^14.3.0",
"copyfiles": "^1.2.0",
"npm-run-all": "^4.0.2",
"rimraf": "^2.6.1"
}
}
Thank you for reading!

First, make sure what services you use, AWS or Azure Web App Services ?
Whatever services you use, I recommand you use git to deploy your web app.
Use git to deploy in azure web app services.
Use git to deploy in aws.
You just make sure your web app can run successfully in local. And the port you use like app.set('port', process.env.PORT || 3000); or const port = process.env.PORT || 3000. Which means you can success run in local with 3000 port.
For more details, you can see my answer in another post.
Azure - Unhandled Exception: System.IO.FileNotFoundException
Concurrently JS application pipeline install and build hangs (Express js for server, Create-React-App for Client)
You can refer to the way of troubleshooting when deploy web app by Action. Hope my answer can help you.

Related

Receive data on front-end React app from webhook

I am building a headless CMS with Strapi. I am testing the webhooks section and want to show the received data from the webhook on my React front-end.
I created a new folder webhooks on my local machine and ran npm init -y.
It created a package.json file with this content in it:
{
"name": "webhooks",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
}
}
I added a index.js file to the root folder with this content and installed express and body-parser:
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
const PORT = 3001
app.use(bodyParser.json())
app.post("/webhook", (req, res) => {
console.log(req.body)
res.status(200).end()
})
app.listen(PORT, () => console.log(`🚀 Server running on port ${PORT}`))
After that I added this line in my package.json:
"start": "node index.js"
So it will start up with npm start instead of node index.js.
I added this URL to my strapi webhooks: http://localhost:3001/webhook and tested the trigger from the Strapi admin. It works fine.
After this I ran npx create-react-app client to create my react front-end app.
My next question is now how can I receive the contents from the webhook in my react front-end app?

Heroku Deployment not working with MongoDb

I created one demo app with ReactJS, NodeJS, MongoDb and Express. Trying to deploy on heroku. It works fine, if i dont use mongo, but as soon as i introduced mongo db. I am getting error cannot GET /.
I am using mongodb atlas. Do I need heroku addon to use database?
server.js
// Import dependencies
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectID;
const mongodb = require('mongodb');
const fs = require('fs');
const moment = require("moment");
require('dotenv').config();
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://<username>:<password>#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
const DATABASE_NAME = "DBNAME";
const port = process.env.PORT || 5000;
const app = express();
// Set our backend port to be either an environment variable or port 5000
// This application level middleware prints incoming requests to the servers console, useful to see incoming requests
app.use((req, res, next) => {
console.log(`Request_Endpoint: ${req.method} ${req.url}`);
next();
});
// Configure the bodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Configure the CORs middleware
app.use(cors());
app.get("/test/", (request, response) => {
response.send({"name":"Hello Test!!!"});
});
var database, userSignUp;
app.listen(port, () => {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
if(error) {
throw error;
}
database = client.db(DATABASE_NAME);
userSignUp = database.collection("UserData");
console.log("Connected to `" + DATABASE_NAME + "`!");
});
})
package.json
{
"name": "testproject",
"version": "1.0.0",
"description": "Learning Deployment",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"client": "cd client && npm start",
"server": "nodemon server.js",
"dev": "concurrently --kill-others-on-fail \"npm run client\" \"npm run server\"",
"client:build": "cd client && npm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Username/TestProject.git"
},
"author": "Ankita Jaiswal",
"license": "ISC",
"bugs": {
"url": "https://github.com/Username/TestProject/issues"
},
"homepage": "https://github.com/Username/TestProject#readme",
"dependencies": {
"body-parser": "^1.19.0",
"concurrently": "^5.3.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"nodemon": "^2.0.7",
"moment": "^2.29.1",
"mongodb": "^3.6.3",
"mongoose": "^5.11.8"
}
}
procfile
web: npm run dev
have tried web: npm start as well.
Just from my limited experience, I've had the same issue and it turned out I forgot to configure my environment variables on Heroku, so my MONGO_URI was undefined. If not that, you can use the Heroku CLI and run heroku logs --tail from the root of your project and might be able to see more about what's going on.
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://<username>:<password>#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
The upper code is incorrect. You have to change < username > and < password > (both include < >) by your usename and your password! Example:
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://kanechan25:kane02052409#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";

Heroku - React application is calling localhost in fetch() requests instead of the Heroku URL for my Express backend

The issue I am having is my React application hosted on Heroku is calling "https://localhost:8000" for it's calls to the Express server.
I have the proxy in package.json set to https://localhost:8000 to call my Express server. From my understanding this is all I need to do and Heroku handles the connection when it is deployed.
When I go to my endpoint like so: https://heroku-app.herokuapp.com/v1/products/:productid my Express server successfully sends back JSON data in the browser, so I do know my Node server is up and running on Heroku. The issue seems to be the React app proxy is not calling the Heroku URL post-deploy.
Here is my React apps package.json:
{
"name": "client",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"proxy": "http://localhost:8000/",
"devDependencies": {
"enzyme-matchers": "^7.0.2"
}
}
This is the package.json file for my server:
{
"name": "stub_boilerplate",
"version": "1.0.0",
"description": "Quick Stub",
"main": "server.js",
"scripts": {
"test": "jest",
"start": "node server/server.js",
"heroku-postbuild": "cd client && npm install --only=dev && npm install && npm run build"
},
"engines": {
"node": "~9.10.1",
"npm": "~5.6.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/manm/xxx.git"
},
"author": "Maison M",
"license": "MIT",
"bugs": {
"url": "https://github.com/maonm/xxx/issues"
}
}
Here is my server.js file. I am setting the port to process.env.PORT || 8000:
const express = require('express');
const app = express();
const port = process.env.PORT || 8000;
//Allows access to enviroment variables in development
require('dotenv').config({ path: __dirname + '/.env' });
//Middleware
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(methodOverride('_method'));
//Serve build folder of client
app.use(express.static(path.join(__dirname, '../client/build')));
app.use('/v1/products', product_routes);
//Error handling
app.use(errorHandler);
//Initialize Express server
app.listen(port, err => {
if (err) console.info(`Error: The server failed to start on ${port}`);
else console.info(`****** Node server is running on ${port} ******`);
});
This is the fetch() request inside of the component:
componentDidMount() {
this.fetchStripePlans();
}
fetchStripePlans = () => {
const stripeProduct = 'prod_FlXXXXXBVn8'; //QS (product)
const url = `http://localhost:8000/v1/products/${stripeProduct}`;
const fetchConfig = {
method: 'GET',
headers: {
'content-type': 'application/json'
}
};
fetch(url, fetchConfig)
.then(data => data.json())
.then(stripe => {
const { data } = stripe;
this.setState({
stripePlans: data
});
})
.catch(err => {
this.setState({
error: true,
errorMessage: err.genericError
});
});
};
This is what I am seeing in the console of the React app:
SignUpContainer.js:48 OPTIONS http://localhost:8000/v1/products/prod_FRon8 net::ERR_CONNECTION_REFUSED
So to me logically, it's not being routed to the Heroku URL. I've scoured a few tutorials on deploying React/Express projects to Heroku and all of them leave the React proxy set to the local host of the Express server. So I am not too sure what is happening here.
In order to make use of the proxy value in your package.json, you must specify a relative URL in your fetch request, such as /v1/products/${stripeProduct}. You should not include the hostname or port in your component.
For reference, see "Running the server and the React app" and "Using the proxied server from React" sections in here: https://www.twilio.com/blog/react-app-with-node-js-server-proxy
Although a GET request usually qualifies as a simple request, the fact that the Content-Type is set as application/json qualifies it as a pre-flight [1] request. Therefore, what happens is that the browser sends a HTTP request before the original GET request by OPTIONS method to check whether it is safe to send the original request.
Try enabling CORS Pre-Flight for your route handler sending the application/json response. You can do this by using the cors [2] middleware in the options handler for your route, like such:
const express = require('express')
cosnt cors = require('cors')
const app = express()
app.options('/products/:id', cors()) // enable pre-flight request for GET request
app.get('/products/:id', cors(), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
[1] https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
[2] https://www.npmjs.com/package/cors

Openshift node app error when restarting

I have a node/socket.io chat app hosted on openshift, and while it starts correctly if i ssh into the server and do "node main.js" (where main.js is the server script that starts the chat), I can't start the app on the server by web interface, where it would go on automatically; If i just start the app by ssh, it would stop working as soon as i exit the terminal.
I get this error when starting the app by the web interface:
Starting Node.js application...
Application is already stopped.
Warning! Could not start Node.js application!
Failed to execute: 'control restart' for /var/lib/openshift/57003fbe7628e1491d00011e/nodejs
In case it's relevant, my package.json file is
{
"name": "rainychat",
"version": "1.0.0",
"description": "rainychat, my chat app",
"main": "main.js",
"dependencies": {
"express": "^4.13.4",
"socket.io": "^1.4.5",
"validator": "^5.1.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "JG",
"license": "ISC"
}
And here you can see the files of the app by ftp:
I can't decode what that error means...
My main.js code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/chat.html'); // /home/redadmin/public_html/rainychat.com
console.log('enviado');
});
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 8080);
app.set('ip', process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1');
http.listen(app.get('port'), app.get('ip'), function () {
console.log('Listening on port ' + app.get('port'));
});
//... More code
If you're creating a new Node project, start with npm init to create the package.json file. You can add the --auto option to give it safe defaults.
Remember, the JSON file must be valid JSON, so test it with jsonlint or a tool like an online validator.
Any dependencies your project has should be spelled out in the package file. This is done automatically with things like npm install express --save.

502 Bad Gateway Deploying Express Generator Template on Elastic Beanstalk

I used the express generator to create a simple express app, which when started on dev works fine on localhost:3000.
When I push this to elastic beanstalk using the eb command-- git aws.push, however, I get a 502 error on the production server.
Looking into the logs, the error I get is:
2014/04/01 19:29:40 [error] 24204#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.2.178, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8081/", host: "macenvexp-env-hqv9ucmzev.elasticbeanstalk.com"
2014/04/01 19:29:40 [error] 24204#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.2.178, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8081/favicon.ico", host: "macenvexp-env-hqv9ucmzev.elasticbeanstalk.com"
I'm using the default nginx configuration. When I run a node.js sample app without Express, it works fine. Here's the express code in app.js:
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes');
var users = require('./routes/user');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
app.get('/', routes.index);
app.get('/users', users.list);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
And here's the package.json file:
{
"name": "macEnvExp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "DEBUG=macEnvExp node bin/www"
},
"dependencies": {
"express": "~3.4.8",
"static-favicon": "~1.0.0",
"morgan": "~1.0.0",
"cookie-parser": "~1.0.1",
"body-parser": "~1.0.0",
"debug": "~0.7.4",
"jade": "~1.3.0"
}
}
And here is bin/www:
#!/usr/bin/env node
var debug = require('debug')('my-application');
var app = require('../app');
app.configure(function(){
app.set('port', process.env.PORT || 3000);
});
console.log(app.get('port'));
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
For clarity, I'll state the answer from the comments.
AWS ELB runs node app.js BEFORE npm start. node app.js doesn't give an error, but it doesn't open any ports.
The solution is to simply rename app.js to anything else except server.js (ie main.js) and reference that in bin/www by pointing to it in the /bin/www file: var app = require('../app'); to var app = require('../main');
Then it should be working correctly!
For clarity, here is what my directory looks like:
The package.json file will get called by ELB when it launches the application server. Here it has the instruction to run the start script node bin/www
This is the bin/www file that gets run. We see the require to ../main and the app.set('port'...)
Then the main.js file that runs the routing and all:
When I created the project, the main.js file was named app.js. The problem this caused was based on the priority ELB start sequences. ELB will launch the application and check first to see if app.js exists -- if it does exist, it runs node app.js, otherwise it will check if package.json exists and try to run npm start.
When the main.js had the name app.js ELB tried to start the whole application by running it. However this file doesn't open any ports.
An alternative to renaming app.js is to create an elastic beanstalk configuration file. Add a .config file into the .ebextensions folder, for example, .ebextensions/34.config. Change the NodeCommand setting in the namespace aws:elasticbeanstalk:container:nodejs to whatever command you want to run to start the server. For example, this is a minimal .config file to run npm start instead of app.js:
option_settings:
- namespace: aws:elasticbeanstalk:container:nodejs
option_name: NodeCommand
value: "npm start"
See http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs_custom_container.html and http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options.html#command-options-nodejs for more information.
Edit:
An even easier way - using the AWS console, Configuration/Software has the "Node command" option - just set that to npm start.
Set running port to 8081
app.set('port', 8081);
Actually, there is another option.
At the Elastic Beanstalk console, inside your app-environment section, there is a Configuration menu item on your left side (right bellow Dashboard menu option). If you click there, you will find many configuration options. Click at Software Configuration and then define which is your node command. There explain the order of commands it tries indeed: "Command to start the Node.js application. If an empty string is specified, app.js is used, then server.js, then "npm start" in that order"
My mistake was at my start command script. It was starting nodemon:
"scripts": {
"start": "NODE_ENV=production && nodemon ./bin/www"
Then I changed to node and it worked:
"scripts": {
"start": "NODE_ENV=production && node ./bin/www"
Hope I helped someone.
If you use port 8081 for running your express app and use sudo for running node server, Your application will be accessed directly from elasticbean url without port numbers, otherwise it will display a 502 Gateway error from nginx.
Nginx proxying 8081 port by default for node app on elastibeanstalk.
Create file: .ebextensions/nodecommand.config and put the option settings below:
option_settings:
aws:elasticbeanstalk:container:nodejs:
NodeCommand: sudo pm2 start server.js (server command with sudo ie. sudo node /bin/www)
You can create another file for container commands: .ebextensions/01_init.config and put the desired commands which will be run before deployment. For example:
container_commands:
01_node_v6_install:
command: sudo curl --silent --location https://rpm.nodesource.com/setup_6.x | bash -
02_install_node:
command: sudo yum -y install nodejs
03_npm_install_gulp_webpack:
command: sudo npm install -g gulp webpack pm2
04_npm_install:
command: sudo npm install
05_webpack_run:
command: sudo webpack
In case anyone did the silly thing I did, make sure your bin folder is committed if you are using express. I had mine in my .gitignore file and this is why I was getting a 502 error.
Just remove /bin from .gitignore, commit, and the deploy changes to EB.
new to AWS and been a while since i webdeved, but was stuck tonight on same issue, and thanks to everyone in the thread, i am very happy to say that basic socket.io tutorial works now like a charm, i was just forgetting one line in package.json :
"scripts":
{
"start": "node app.js"
}
oh, and port !
the only thing i kept from elasticbean sample node.js app is this value instead of pure 3000 value :
var port = process.env.PORT || 3000;
Note: I ran into this issue and none of the solutions were working for me.
My solution was to make sure the devDependencies in package.json were actually in dependencies.
For example:
{
"name": "whaler-test",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"create-db": "cd dynamodb && node createDonorsTable.js && cd ..",
"delete-db": "cd dynamodb && node deleteDonorsTable.js && cd ..",
"load-data": "cd dynamodb && node loadDonorsData.js && cd ..",
"read-data": "cd dynamodb && node readDataTest.js && cd .."
},
"dependencies": {
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"http-errors": "~1.6.2",
"jade": "~1.11.0",
"morgan": "~1.9.0",
"nodemon": "1.17.5",
"cors": "2.8.4",
"aws-sdk": "^2.270.1"
}
}
Not:
{
"name": "whaler-test",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"create-db": "cd dynamodb && node createDonorsTable.js && cd ..",
"delete-db": "cd dynamodb && node deleteDonorsTable.js && cd ..",
"load-data": "cd dynamodb && node loadDonorsData.js && cd ..",
"read-data": "cd dynamodb && node readDataTest.js && cd .."
},
"dependencies": {
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"http-errors": "~1.6.2",
"jade": "~1.11.0",
"morgan": "~1.9.0",
"nodemon": "1.17.5"
},
devDependencies {
"cors": "2.8.4",
"aws-sdk": "^2.270.1"
}
}

Resources