node.js 502 Bad Gateway 在 Elastic Beanstalk 上部署 Express Generator 模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22795357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:06:03  来源:igfitidea点击:

502 Bad Gateway Deploying Express Generator Template on Elastic Beanstalk

node.jsamazon-web-servicesnginxexpress

提问by user3486588

I used the express generator to create a simple express app, which when started on dev works fine on localhost:3000.

我使用 express 生成器创建了一个简单的 express 应用程序,它在 dev 上启动时可以在 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.

但是,当我使用 eb 命令 - git aws.push 将其推送到弹性 beantalk 时,我在生产服务器上收到 502 错误。

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:

我正在使用默认的 nginx 配置。当我在没有 Express 的情况下运行 node.js 示例应用程序时,它工作正常。这是 app.js 中的 express 代码:

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:

这是 package.json 文件:

{
  "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:

这里是 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);
});

回答by Federico

For clarity, I'll state the answer from the comments.

为了清楚起见,我将从评论中给出答案。

AWS ELB runs node app.jsBEFORE npm start. node app.jsdoesn't give an error, but it doesn't open any ports.

AWS ELB 运行node app.js之前npm startnode app.js不会出错,但不会打开任何端口。

The solution is to simply rename app.jsto 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');

解决的办法是简单地重命名app.js以任何其他除外server.js(即main.js)和参考,在通过指向它在/ bin / WWW文件斌/ WWW:var app = require('../app');var app = require('../main');

Then it should be working correctly!

那么它应该可以正常工作!



For clarity, here is what my directory looks like:

为了清楚起见,这是我的目录的样子:

The package.jsonfile will get called by ELB when it launches the application server. Here it has the instruction to run the start script node bin/wwwenter image description here

package.json文件将在 ELB 启动应用程序服务器时被调用。这里有运行启动脚本的指令node bin/www在此处输入图片说明

This is the bin/wwwfile that gets run. We see the require to ../mainand the app.set('port'...)enter image description here

这是bin/www运行的文件。我们看到需要../mainapp.set('port'...)在此处输入图片说明

Then the main.jsfile that runs the routing and all: enter image description here

然后main.js是运行路由的文件和所有: 在此处输入图片说明

When I created the project, the main.jsfile 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.jsexists -- if it does exist, it runs node app.js, otherwise it will check if package.jsonexists and try to run npm start. When the main.jshad the name app.jsELB tried to start the whole application by running it. However this file doesn't open any ports.

当我创建项目时,main.js文件名为app.js. 这导致的问题是基于优先级 ELB 启动序列。ELB 将启动应用程序并首先检查是否app.js存在——如果存在,则运行node app.js,否则将检查是否package.json存在并尝试运行npm start。当main.js有名称app.jsELB试图通过运行它来启动整个应用程序。但是这个文件没有打开任何端口。

回答by Logan Pickup

An alternative to renaming app.jsis to create an elastic beanstalk configuration file. Add a .configfile into the .ebextensionsfolder, for example, .ebextensions/34.config. Change the NodeCommandsetting in the namespace aws:elasticbeanstalk:container:nodejsto whatever command you want to run to start the server. For example, this is a minimal .configfile to run npm startinstead of app.js:

重命名的替代方法app.js是创建一个弹性 beanstalk 配置文件。将.config文件添加到文件.ebextensions夹中,例如.ebextensions/34.config. NodeCommand将命名空间中的设置更改为aws:elasticbeanstalk:container:nodejs要运行以启动服务器的任何命令。例如,这是一个.config要运行的最小文件,npm start而不是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.htmland http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options.html#command-options-nodejsfor more information.

请参阅http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs_custom_container.htmlhttp://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options.html#command-options -nodejs了解更多信息。

Edit: An even easier way - using the AWS console, Configuration/Software has the "Node command" option - just set that to npm start.

编辑:一种更简单的方法 - 使用 AWS 控制台,配置/软件具有“节点命令”选项 - 只需将其设置为npm start.

回答by Can

Set running port to 8081

将运行端口设置为 8081

app.set('port', 8081);

回答by Marianna Spirandelli

Actually, there is another option.

实际上,还有另一种选择。

At the Elastic Beanstalk console, inside your app-environment section, there is a Configurationmenu item on your left side (right bellow Dashboard menu option). If you click there, you will find many configuration options. Click at Software Configurationand 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"

在 Elastic Beanstalk 控制台的应用程序环境部分中,左侧有一个配置菜单项(仪表板菜单选项的右侧)。如果单击那里,您会发现许多配置选项。单击软件配置,然后定义哪个是您的节点命令。那里解释了它确实尝试的命令的顺序:“启动 Node.js 应用程序的命令。如果指定了空字符串,则使用 app.js,然后使用 server.js,然后按该顺序使用“npm start””

My mistake was at my start command script. It was starting nodemon:

我的错误是在我的启动命令脚本中。它正在启动 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.

希望我帮助了某人。

回答by maniyadv

If you use port 8081for running your express app and use sudofor 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.

如果你使用端口8081来运行你的 express 应用程序并sudo用于运行节点服务器,你的应用程序将直接从没有端口号的 elasticbean url 访问,否则它将显示来自 nginx 的 502 网关错误。

Nginx proxying 8081 port by default for node app on elastibeanstalk.

Nginx proxying 8081 port by default for node app on elastibeanstalk.

Create file: .ebextensions/nodecommand.configand put the option settings below:

创建文件:.ebextensions/nodecommand.config并将选项设置放在下面:

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.configand put the desired commands which will be run before deployment. For example:

您可以为容器命令创建另一个文件:.ebextensions/01_init.config并放置将在部署之前运行的所需命令。例如:

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

回答by Gaz_Edge

In case anyone did the silly thing I did, make sure your binfolder is committed if you are using express. I had mine in my .gitignorefile and this is why I was getting a 502 error.

如果有人做了我所做的愚蠢的事情,请确保您的bin文件夹在您使用 express 时已提交。我的.gitignore文件中有我的,这就是我收到 502 错误的原因。

Just remove /binfrom .gitignore, commit, and the deploy changes to EB.

只需/bin.gitignore、提交和部署更改到 EB。

回答by khalil

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 :

AWS 新手,自从我开发网络以来已经有一段时间了,但今晚被困在同一个问题上,感谢线程中的每个人,我很高兴地说基本的 socket.io 教程现在就像一个魅力,我只是忘记了一个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 :

哦,还有端口!我从 elasticbean 示例 node.js 应用程序中保留的唯一值是这个值而不是纯 3000 值:

var port = process.env.PORT || 3000;

回答by Luis Pedraza

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.

我的解决方案是确保 package.json 中的 devDependencies 实际上是依赖项。

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"
  }
}