+86 135 410 16684Mon. - Fri. 10:00-22:00

佈署 Node.js Application 至 Elastic Beanstalk 上 – 以 Express 4.x 為例

佈署 Node.js Application 至 Elastic Beanstalk 上 - 以 Express 4.x 為例

佈署 Node.js Application 至 Elastic Beanstalk 上 – 以 Express 4.x 為例

參考連結

主要有以下幾個步驟:

  1. 透過 express-generator 創建 express app
  2. 創建一個 Git repository
  3. 取得 access key id 與 secret access key (若已有可跳過)
  4. 設定與安裝 eb command line tool
  5. 利用 eb command line tool 初始化並創建 application 運行環境
  6. 設定 App 的 package.json
  7. 上傳並佈署 App

透過 express-generator 創建 express app

$ npm install -g express-generator

//創建一個名為 `myapp` 的 express app
$ express --css stylus myapp

測試是否能正常執行

$ cd myapp
$ npm install
$ npm start

創建一個 Git repository

將剛創立的 express app 初始化成 git repository

$ cd myapp  
$ git init

取得 access key id 與 secret access key (若已有可跳過)

參考連結

  1. 先至 Security Credentials頁面
  2. 點選 Dashboard 裡點選 Users 選項,並選擇自己的 User Name
  3. 接著在 Security Credentials 區域裡選擇 Manage Access Keys
  4. 最後點選 Create Access Key,並且將 .csv 檔案載下來,妥善保管
  5. access key id 與 secret access key 皆在剛下載的 .csv 檔案裡頭

安裝與設定 eb command line tool

參考連結

EB command line tool is a command line client for interacting with the AWS Elastic Beanstalk APIs.

Important :

The command line tools used in this guide require Ruby version 1.8.7+ or Ruby version 1.9.2+ to run. To view and download Ruby clients for a range of platforms, including Linux/UNIX and Windows, go to http://www.ruby- lang.org/en/.

  1. 下載eb command line tool
  2. 將下載下來的壓縮檔解開後,移到自己喜歡的位置,並且設定 PATH 使其可方便執行
    //假設將資料夾存放在 "/Applications/" 底下
    //若為 Linux系統,將 macosx 替換成 linux 即可
    
    $ export PATH=$PATH:/Applications/AWS-ElasticBeanstalk-CLI-2.6.3/eb/macosx/python2.7/
    
  3. 若想要將此設定永久保留,則將上述的 export 指令寫入 ~/.bash_profile 裡頭(Linux 的話為 ~/.bashrc
    $ vim ~/.bash_profile           
    //將 " export PATH=$PATH:/Applications/AWS-ElasticBeanstalk-CLI-2.6.3/eb/macosx/python2.7/ " 寫入 ~/.bash_profile 中
    
    $ source ~/.bash_profile    //使設定立即生效
    
  4. 測試 eb 指令是否設置成功
    $ eb
    =>
        Error: too few arguments
        usage: eb {COMMAND} [options]
        Try eb --help for more information.
    

利用 eb command line tool 初始化並創建 application 運行環境

參考連結

  1. 回到我們一開始創建的 Git repository 底下
    $ cd myapp
    
  2. 初始化 Elastic Beanstalk 設定
    $ eb init
    
    //有很多配置要求,根據自身需求選擇即可(以下省略許多)        
    => Enter your AWS Access Key ID (current value is "AKIAIOSFODNN7EXAMPLE"): <input your Access Key ID>
    
    => Enter your AWS Secret Access Key (current value is "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"):  <input your Secret Access Key>
    
    => Enter an AWS Elastic Beanstalk application name (auto-generated value is "node-express"): <input your app name>
    
    => Available environment tiers are:
        1) WebServer::Standard::1.0
        2) Worker::SQS/HTTP::1.0
    //選擇 1
    
    => Select a solution stack (current value is "64bit Amazon Linux 2014.03 v1.0.4 running Node.js").
    //選擇運行環境與系統
    //選擇 9 => 64bit Amazon Linux 2014.03 v1.0.4 running Node.js
    
    => Available environment types are: 
        1) LoadBalanced
        2) SingleInstance
    //選擇 1
    
    ...(省略 RDS DB 配置)
    
  3. 透過 eb start 初始化並創建範例App
    $ eb start
    
    //若你之前已經有 commit 過,它會詢問你是否使用最新的 commit 版本,暫時先選否。
    
  4. 接著便能透過 AWS 給你的網址看到輸出的範例 App

設定 App 的 package.json

AWS Elastic Beanstalk 透過讀取 package.json 的設定決定如何運行 Node.js App。

查看剛剛所創建的 myapp 的檔案結構:

//此時 myapp 檔案結構如下
$ tree myapp
myapp
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.styl
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.jade
    ├── index.jade
    └── layout.jade   

查看 myapp 下的 package.json

package.json
{
  "name": "myapp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "express": "~4.2.0",
    "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",
    "stylus": "0.42.3"
  }
}

可以發現產生器所產生的 express app 是透過 node ./bin/www 去執行的,而AWS Elastic Beanstalk 也是依據 scripts 下的 start 參數去執行的。

Important :

AWS Elastic Beanstalk 在執行 node.js app時,會預設去執行 node app.js,而產生器產生的主要 express server 的檔案也恰好取名為 app.js,若直接將此設定上傳至主機,會導致執行時,什麼事情都沒發生,而產生了 502 Bad Gateway 的 error 。因此需將 app.js 重新命名成 app.jsserver.js (沒錯,server.js 也不行。)以外的名稱,例如 main.js。並將 /bin 底下的 wwwvar app = require('../app'); 改成 var app = require('../main');

完整程式碼如下:

.bin/www
#!/usr/bin/env node
var debug = require('debug')('myapp');
var app = require('../main');

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});

另外就是 process.env.PORT 這個參數可以指向真正佈署的主機對應 80 Port 的實際 Port。若想要使用其他 Port,則要在 AWS 中另外開啟才行。

上傳並佈署 App

Elastic Beanstalk 有兩種上傳方式:

  • 使用 eb command line tool 上傳
  • 使用 web interface 上傳

使用 eb command line tool 上傳

  1. 回到 myapp 資料夾底下
    $ cd myapp
    
  2. 若有修改,先將修改後的結果 commit
    $ git add .
    $ git commit -a -m "my first change."
    
  3. 將 App 上傳,並且佈署
    $ git aws.push
    
  4. 等待佈署完成,並且再次查看 App 是否有成功佈署

Important :

git aws.push 時如果有報 ImportError: No module named boto 的錯誤,請先執行以下的指令安裝 boto

    $ pip install boto
    $ pip freeze > reqIuirements.txt

若不存在 pip 指令,則需透過以下方式安裝 pip:

  1. 先下載這個檔案: get-pip.py, 備用連結
  2. 然後到下載位置安裝 get-pip.py
    $ cd Downloads
    $ sudo python get-pip.py
    

使用 web interface 上傳

  1. 先到 AWS Elastic Beanstalk console
  2. 將要上傳的 App 壓縮成 .zip

    Important : 壓縮時,不可以直接對整個資料夾進行壓縮,而是要點開資料夾,進行全選壓縮。否則會造成 AWS Elastic Beanstalk 因找不到 package.json 而產生的 502 Bad Gateway 的錯誤。

  3. 點擊 Upload and Deploy 按鈕,並選擇上傳壓縮檔,再按下 Deploy 按鈕後,即可等待佈署完成。
    AWS_Upload
  4. 查看 App 是否有成功佈署