502 Bad Gateway Deploying Express Generator Template on Elastic Beanstalk
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
.