program story

502 잘못된 게이트웨이 Elastic Beanstalk에 Express 생성기 템플릿 배포

inputbox 2020. 12. 15. 19:17
반응형

502 잘못된 게이트웨이 Elastic Beanstalk에 Express 생성기 템플릿 배포


나는 익스프레스 생성기를 사용하여 간단한 익스프레스 앱을 만들었는데, dev에서 시작하면 localhost : 3000에서 잘 작동합니다.

eb 명령 (git aws.push)을 사용하여이를 Elastic beanstalk에 푸시하면 프로덕션 서버에서 502 오류가 발생합니다.

로그를 살펴보면 내가 얻는 오류는 다음과 같습니다.

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"

기본 nginx 구성을 사용하고 있습니다. Express없이 node.js 샘플 앱을 실행하면 제대로 작동합니다. 다음은 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;

다음은 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"
  }
}

그리고 여기에 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);
});

명확성을 위해 댓글의 답변을 설명하겠습니다.

AWS ELB는 실행 node app.js하기 전에 npm start. node app.js오류가 발생하지 않지만 포트가 열리지 않습니다.

이 솔루션은 단순히 이름을 변경하는 것입니다 app.js제외하고 무엇에 server.js(예 main.js) 참조 그 / 빈 / www가 파일에 가리키는하여 빈 / www가에서 : var app = require('../app');var app = require('../main');

그러면 제대로 작동해야합니다!


명확성을 위해 다음은 내 디렉토리의 모습입니다.

package.json파일은 응용 프로그램 서버를 시작할 때 ELB에 의해 호출됩니다. 여기에 시작 스크립트를 실행하는 지침이 있습니다.node bin/www 여기에 이미지 설명 입력

이것은 bin/www실행 되는 파일입니다. 우리는 요구 사항 ../mainapp.set('port'...) 여기에 이미지 설명 입력

그런 다음 main.js라우팅 및 모두를 실행 하는 파일 :여기에 이미지 설명 입력

프로젝트를 만들 때 main.js파일 이름은 app.js. 이로 인해 발생한 문제는 우선 순위 ELB 시작 시퀀스에 기반했습니다. ELB는 응용 프로그램을 시작하고 먼저 app.js존재 node app.js하는지 확인합니다. package.json존재하는 경우 실행되고 , 그렇지 않으면 존재 하는지 확인 하고 실행을 시도합니다 npm start. (가) 때 main.js이름을했다 app.jsELB 그것을 실행하여 전체 응용 프로그램을 시작했습니다. 그러나이 파일은 포트를 열지 않습니다.


이름 바꾸기의 대안 app.js은 탄력적 beantalk 구성 파일을 만드는 것입니다. 폴더에 .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"

참조 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 를 참조하십시오.

편집 : 더 쉬운 방법-AWS 콘솔을 사용하는 구성 / 소프트웨어에는 "노드 명령"옵션이 npm start있습니다.이 옵션을 .


실행 포트를 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.


AWS를 처음 사용하고 웹 개발 한 지 오래되었지만 오늘 밤 같은 문제에 갇혀 있었고 스레드의 모든 사람 덕분에 기본 socket.io 자습서가 이제 매력처럼 작동한다고 말하게되어 매우 기쁩니다. package.json의 줄 :

"scripts":
{
"start": "node app.js"
}

아, 그리고 항구! elasticbean 샘플 node.js 앱에서 유지 한 유일한 것은 순수한 3000 값 대신이 값입니다.

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

참고 :이 문제가 발생했으며 어떤 솔루션도 나를 위해 작동하지 않았습니다.

내 해결책은 package.json의 devDependencies가 실제로 종속성에 있는지 확인하는 것이 었습니다.

예를 들면 :

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

아니:

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

참조 URL : https://stackoverflow.com/questions/22795357/502-bad-gateway-deploying-express-generator-template-on-elastic-beanstalk

반응형