"502 Bad Gateway" deploying hapi.js to AWS Beanstalk?

Adron picture Adron · Aug 12, 2014 · Viewed 7.2k times · Source

I've built a very simple hapi.js app with the following code.

var Hapi = require('hapi');
var server = new Hapi.Server(3000);

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        reply('Hello, world!');
    }
});

server.start(function () {
    console.log('Server running at:', server.info.uri);
});

However I keep getting a "502 Bad Gateway" error upon deploy. I'm using a standard zip & upload method to deploy. The zip file contains a service.js file with the code above and a package.json file as shown below.

{
  "name": "hapi_aws_testing",
  "version": "0.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "hapi": "^6.4.0"
  },
  "engines"        : {
    "node": "0.10.26"
  }
}

I've tried deploying with the node.js engines section removed, and also set it to 0.10.29 and then realized that the version of node.js available in Beanstalk on the 1.0.4 AMI images was 0.10.26, so changed it here to that version. I've tried it locally and all runs well.

In the error log I've got the following two logs that show the code running...

-------------------------------------
/var/log/nodejs/nodejs.log
-------------------------------------
Server running at: http://ip-172-31-3-9:3000

and then the errors when I try to hit the server with a browser.

-------------------------------------
/var/log/nginx/error.log
-------------------------------------
2014/08/12 02:07:24 [error] 3457#0: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.13.177, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8081/", host: "consociation-test.elasticbeanstalk.com"
2014/08/12 02:07:26 [error] 3457#0: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.13.177, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8081/", host: "consociation-test.elasticbeanstalk.com"

Answer

robbles picture robbles · Aug 12, 2014

It looks like your server is listening on port 3000, but from the nginx log file, it's setup to proxy to a node app listening on port 8081 (See the "upstream:" part).

You might want to try using the PORT environment variable instead of hard coding it to either value though - I'm pretty sure EB exposes this to your app. That'll make sure updates to the runtime don't break your setup.