Elastic Beanstalkを利用すると、 Webアプリで必要とされる モニタリング
負荷分散
スケーリング
といった機能をサポートしてくれます。ここでは、Express(Node.jsのWebフレームワーク)
をElastic Beanstalk上にデプロイしてみます。
Elastic Beanstalkの概要
Elastic Beanstalkは、アプリケーション
という大枠のなかに、1つ以上の 環境
を構築して利用します。
アプリケーション
アプリケーションバージョン
- バージョンラベル
- 作成日
- ソース
- デプロイ先環境
保存された設定
環境
- 環境A
- 環境枠
- ウェブサーバー
- ワーカー環境
- プラットフォーム(
Go
Node.js
など) - 環境変数
- インスタンスタイプ
- etc
- 環境枠
- 環境B
- 同様
- 環境A
ローカルでExpressアプリの作成
nodeのバージョンは以下の通りです。Elastic Beanstalkでも同じバージョンを利用します。
$ node -v
v10.15.1
express-generator でプロジェクトを生成します。
$ npx express eb-testapp
warning: the default view engine will not be jade in future releases
warning: use `--view=jade' or `--help' for additional options
create : eb-testapp/
create : eb-testapp/public/
create : eb-testapp/public/javascripts/
create : eb-testapp/public/images/
create : eb-testapp/public/stylesheets/
create : eb-testapp/public/stylesheets/style.css
create : eb-testapp/routes/
create : eb-testapp/routes/index.js
create : eb-testapp/routes/users.js
create : eb-testapp/views/
create : eb-testapp/views/error.jade
create : eb-testapp/views/index.jade
create : eb-testapp/views/layout.jade
create : eb-testapp/app.js
create : eb-testapp/package.json
create : eb-testapp/bin/
create : eb-testapp/bin/www
change directory:
$ cd eb-testapp
install dependencies:
$ npm install
run the app:
$ DEBUG=eb-testapp:* npm start
パッケージをインストールして、アプリを起動します。
$ cd eb-testapp
$ npm install
$ DEBUG=eb-testapp:* npm start
ブラウザでアクセスできることを確認できました。
EB CLIのインストール
AWS CLI
とは別に Elastic Beanstalk用のCLI(EB CLI)
が提供されています。コンソールからでも環境構築、デプロイの作業ができますが、ここでは、EB CLI
を利用して各種作業を進めます。
$ python -V
Python 3.6.5
$
$ pip -V
pip 9.0.3 from /Users/xxxx/.pyenv/versions/3.6.5/lib/python3.6/site-packages (python 3.6)
$
$ pip install awsebcli --upgrade
EB CLI
をインストールできました。
$ eb --version
EB CLI 3.14.13 (Python 3.6.5)
$
$ eb -h
usage: eb (sub-commands ...) [options ...] {arguments ...}
Welcome to the Elastic Beanstalk Command Line Interface (EB CLI).
For more information on a specific command, type "eb {cmd} --help".
commands:
abort Cancels an environment update or deployment.
appversion Listing and managing application versions
clone Clones an environment.
codesource Configures the code source for the EB CLI to use by default.
config Modify an environment's configuration. Use subcommands to manage saved configurations.
console Opens the environment in the AWS Elastic Beanstalk Management Console.
create Creates a new environment.
deploy Deploys your source code to the environment.
events Gets recent events.
health Shows detailed environment health.
init Initializes your directory with the EB CLI. Creates the application.
labs Extra experimental commands.
list Lists all environments.
local Runs commands on your local machine.
logs Gets recent logs.
open Opens the application URL in a browser.
platform Commands for managing platforms.
printenv Shows the environment variables.
restore Restores a terminated environment.
scale Changes the number of running instances.
setenv Sets environment variables.
ssh Opens the SSH client to connect to an instance.
status Gets environment information and status.
swap Swaps two environment CNAMEs with each other.
tags Allows adding, deleting, updating, and listing of environment tags.
terminate Terminates the environment.
upgrade Updates the environment to the most recent platform version.
use Sets default environment.
optional arguments:
-h, --help show this help message and exit
--debug toggle debug output
--quiet suppress all output
-v, --verbose toggle verbose output
--profile PROFILE use a specific profile from your credential file
-r REGION, --region REGION
use a specific region
--no-verify-ssl don't verify AWS SSL certificates
--version show application/version info
To get started type "eb init". Then type "eb create" and "eb open"
EC2キーペアの作成
Elastic Beanstalkで作成したインスタンスにSSH接続する際に利用するキーペアを作成します。
ここでは、AWS CLI
で作成します。--key-name
の値は、適宜わかりやすい名前にしてください。
$ aws ec2 create-key-pair \
--key-name eb-testapp \
--query 'KeyMaterial' \
--output text > eb-testapp.pem
プライベートキーを eb-testapp.pem
に書き込んでいます。SSH接続するときに利用します。権限を変更しておきます。
$ chmod 400 eb-testapp.pem
EBのアプリケーション、環境構築
eb init
( アプリの作成, 環境のデフォルト設定 )
eb init
でElastic Beanstalkの「アプリケーション構築」と「環境のデフォルト設定ファイル( .elasticbeanstalk/config.yml
)の生成」を行います。
$ eb init
Select a default region
1) us-east-1 : US East (N. Virginia)
2) us-west-1 : US West (N. California)
3) us-west-2 : US West (Oregon)
4) eu-west-1 : EU (Ireland)
5) eu-central-1 : EU (Frankfurt)
6) ap-south-1 : Asia Pacific (Mumbai)
7) ap-southeast-1 : Asia Pacific (Singapore)
8) ap-southeast-2 : Asia Pacific (Sydney)
9) ap-northeast-1 : Asia Pacific (Tokyo)
10) ap-northeast-2 : Asia Pacific (Seoul)
11) sa-east-1 : South America (Sao Paulo)
12) cn-north-1 : China (Beijing)
13) cn-northwest-1 : China (Ningxia)
14) us-east-2 : US East (Ohio)
15) ca-central-1 : Canada (Central)
16) eu-west-2 : EU (London)
17) eu-west-3 : EU (Paris)
18) eu-north-1 : EU (Stockholm)
(default is 3): 9
Enter Application Name
(default is "eb-testapp"):
Application eb-testapp has been created.
It appears you are using Node.js. Is this correct?
(Y/n): y
Cannot setup CodeCommit because there is no Source Control setup, continuing with initialization
Do you want to set up SSH for your instances?
(Y/n): y
Select a keypair.
1) eb-testapp
2) [ Create new KeyPair ]
(default is 1): 1
keypair
は先ほど作成した eb-testapp
を指定します。
アプリケーションの構築と .elasticbeanstalk/config.yml
の生成が行われました。
$ cat .elasticbeanstalk/config.yml
branch-defaults:
default:
environment: null
group_suffix: null
global:
application_name: eb-testapp
branch: null
default_ec2_keyname: eb-testapp
default_platform: Node.js
default_region: ap-northeast-1
include_git_submodules: true
instance_profile: null
platform_name: null
platform_version: null
profile: null
repository: null
sc: null
workspace_type: Application
eb create
( 環境作成, デプロイ )
eb create
でElastic Beanstalkの 環境
を構築します。
$ eb create --vpc
Enter Environment Name
(default is eb-testapp-dev):
Enter DNS CNAME prefix
(default is eb-testapp-dev):
Select a load balancer type
1) classic
2) application
3) network
(default is 2): 2
Enter the VPC ID: vpc-xxxxxxxxxxxxxxxxxxxx
Do you want to associate a public IP address? (Y/n): y
Enter a comma-separated list of Amazon EC2 subnets: subnet-xxxxxxxxxxxxxxxxx,subnet-yyyyyyyyyyyyyyyyy
Enter a comma-separated list of Amazon ELB subnets: subnet-xxxxxxxxxxxxxxxxx,subnet-yyyyyyyyyyyyyyyyy
Do you want the load balancer to be public? (Select no for internal) (Y/n): y
Enter a comma-separated list of Amazon VPC security groups:
Creating application version archive "app-190331_143503".
Uploading eb-testapp/app-190331_143503.zip to S3. This may take a while.
Upload Complete.
Environment details for: eb-testapp-dev
Application name: eb-testapp
Region: ap-northeast-1
Deployed Version: app-190331_143503
Environment ID: e-xxxxxxxxxxx
Platform: arn:aws:elasticbeanstalk:ap-northeast-1::platform/Node.js running on 64bit Amazon Linux/4.8.1
Tier: WebServer-Standard-1.0
CNAME: eb-testapp-dev.ap-northeast-1.elasticbeanstalk.com
Updated: 2019-03-31 05:35:10.599000+00:00
Printing Status:
2019-03-31 05:35:09 INFO createEnvironment is starting.
2019-03-31 05:35:10 INFO Using elasticbeanstalk-ap-northeast-1-xxxxxxxxxxx as Amazon S3 storage bucket for environment data.
2019-03-31 05:35:34 INFO Created target group named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 05:35:34 INFO Created security group named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 05:35:50 INFO Created security group named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 05:36:05 INFO Created Auto Scaling launch configuration named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 05:37:23 INFO Created Auto Scaling group named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 05:37:23 INFO Waiting for EC2 instances to launch. This may take a few minutes.
2019-03-31 05:37:38 INFO Created Auto Scaling group policy named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 05:37:39 INFO Created Auto Scaling group policy named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 05:37:39 INFO Created CloudWatch alarm named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 05:37:39 INFO Created CloudWatch alarm named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 05:38:13 INFO Created load balancer named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 05:38:29 INFO Created Load Balancer listener named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 05:39:58 INFO Successfully launched environment: eb-testapp-dev
--vpcオプション
を付与したので、下記設定も行いました。事前に作成したVPC, サブネットを設定しました。
項目 | 説明 |
---|---|
Enter the VPC ID | VPCのIDを入力 |
Do you want to associate a public IP address? (Y/n) | Public IPを紐づけるか |
Enter a comma-separated list of Amazon EC2 subnets | EC2のサブネット。 今回は、Publicサブネットを指定 |
Enter a comma-separated list of Amazon ELB subnets | ELBのサブネット。 今回は、EC2と同様 |
Do you want the load balancer to be public? (Select no for internal) (Y/n) | ELBをインターネットに公開するか |
Enter a comma-separated list of Amazon VPC security groups | 適用したいSGを指定 |
ここまでの作業で アプリケーション
と 環境
の構築が完了しました。環境は、ヘルスチェックが失敗しているようで赤色になっています。この後の作業で対応します。
.ebextensionsを追加
先ほど環境のヘルスチェックに失敗していましたが、これは、nodeアプリを起動してないためです。
デプロイ時に npm start
を実行してnodeアプリを起動するように調整します。
デプロイ時に追加で処理を入れたい場合、.ebextensionsフォルダ
を作り、その中に処理を記述します。
$ mkdir .ebextensions
$ touch .ebextensions/options.config
以下内容を記述します。
option_settings:
aws:elasticbeanstalk:container:nodejs:
NodeCommand: "npm start"
eb deploy
( デプロイ )
今行った変更を反映させるために eb deploy
でデプロイします。
$ eb deploy
Creating application version archive "app-190331_150903".
Uploading eb-testapp/app-190331_150903.zip to S3. This may take a while.
Upload Complete.
2019-03-31 06:09:09 INFO Environment update is starting.
2019-03-31 06:09:56 INFO Deploying new version to instance(s).
2019-03-31 06:10:58 INFO New application version was deployed to running EC2 instances.
2019-03-31 06:10:58 INFO Environment update completed successfully.
確認
アプリケーションの確認
今度は緑色になりました。
今回は環境を1つしか作成してないですが、複数作成した場合、この画面で複数の環境の状態を確認できます。
option_settings
で設定した内容が反映されています。
ソースはS3に格納されています。過去のソースを利用して環境を立ち上げることもできます。
ELBとEC2のSGを確認
ELBに割り当てられたSG( sg-xxxxxxxxxxxxxxxxxxxxx
)
インバウンドルールは以下のようになっていました。
ポート | プロトコル | ソース |
---|---|---|
80 | tcp | 0.0.0.0/0 |
- HTTP接続はどこからでもアクセス可能な状態です。
EC2に割り当てられたSG( sg-yyyyyyyyyyyyyyyyyyyy
)
インバウンドルールは以下のようになっていました。
ポート | プロトコル | ソース |
---|---|---|
80 | tcp | sg-xxxxxxxxxxxxxxxxxxxxx |
22 | tcp | 0.0.0.0/0 |
- HTTP接続は
sg-xxxxxxxxxxxxxxxxxxxxx
が割り当てられたインスタンスからのみアクセス可能な状態です。- ELBからのみアクセス可能な状態です。
- EC2のパブリックIPアドレスでHTTP接続できないようになっています。
- SSH接続はどこからでもアクセス可能な状態です。
環境にブラウザからアクセス
ELBのDNS名でアクセスできるか確認します。
EC2インスタンスにSSH接続
対象インスタンスのIPv4 パブリックIP
を確認します。
通常、インターネットからはSSH接続できないように設定しますが、いまいまはアクセスできる状態です。
以下のように、eb-testapp.pem
と IPv4 パブリックIP
を指定してアクセスします。
$ ssh -i eb-testapp.pem ec2-user@xx.xx.xx.xx
_____ _ _ _ ____ _ _ _
| ____| | __ _ ___| |_(_) ___| __ ) ___ __ _ _ __ ___| |_ __ _| | | __
| _| | |/ _` / __| __| |/ __| _ \ / _ \/ _` | '_ \/ __| __/ _` | | |/ /
| |___| | (_| \__ \ |_| | (__| |_) | __/ (_| | | | \__ \ || (_| | | <
|_____|_|\__,_|___/\__|_|\___|____/ \___|\__,_|_| |_|___/\__\__,_|_|_|\_\
Amazon Linux AMI
This EC2 instance is managed by AWS Elastic Beanstalk. Changes made via SSH
WILL BE LOST if the instance is replaced by auto-scaling. For more information
on customizing your Elastic Beanstalk environment, see our documentation here:
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html
[ec2-user@ip-xx-xx-xx-xx ~]$
[ec2-user@ip-xx-xx-xx-xx ~]$
[ec2-user@ip-xx-xx-xx-xx ~]$ pwd
/home/ec2-user
[ec2-user@ip-xx-xx-xx-xx ~]$ cd /var/app/current/
[ec2-user@ip-xx-xx-xx-xx current]$
[ec2-user@ip-xx-xx-xx-xx current]$ ls
app.js bin eb-testapp.pem node_modules package.json package-lock.json public README.md routes views
[ec2-user@ip-xx-xx-xx-xx current]$
補足) SSH接続のアクセス制限を調整
Elastic Beanstalkの作成時にkeypairを指定した場合、SSH接続可能なIPが 0.0.0.0/0
となっています。
ポート | プロトコル | ソース |
---|---|---|
80 | tcp | ELBに割り当てたSG |
22 | tcp | 0.0.0.0/0 |
どこからでもSSH接続できるのは良くないので、アクセス制限を調整します。
まず、セキュリティグループを作成します。ソースにはSSH接続を許可したいIPを指定しています。
次に .ebextensions
でSSH許可設定をオーバーライドします。
option_settings:
aws:autoscaling:launchconfiguration:
EC2KeyName: eb-testapp
SSHSourceRestriction: tcp, 22, 22, 127.0.0.1/32
SecurityGroups: sg-xxxxxxxxxxxxxxxxxxxx
デプロイ後、EC2のインバウンドルールは以下のようになりました。
ポート | プロトコル | ソース |
---|---|---|
22 | tcp | sg-xxxxxxxxxxxxxxxxxxxxで許可したIP |
80 | tcp | ELBに割り当てたSG |
22 | tcp | 127.0.0.1/32 |
CloudFormation
Elastic Beanstalkで生成したAWSリソースはCloudFormationで確認できます。Load Balancer
などが生成されていることを確認できます。
IAMロールについて
デフォルトのIAMロールの設定です。
- Elastic Beanstalkのサービスロール
aws-elasticbeanstalk-service-role
- EC2のインスタンスプロファイル
aws-elasticbeanstalk-ec2-role
独自のIAMロールに紐づけられたインスタンスプロファイルを利用したい場合、上記画面で変更できます。
または、環境作成時に、 --instance_profileオプション
で指定することもできます。
eb create --vpc --instance_profile xxxxxxxxxxxxxxxxxxxx
CloudWatch Logsの利用
ログ内容はプラットフォームごとに固定されますが、Beanstalkの設定で CloudWatch Logs
へログ出力させることもできます。
.ebextensions
でCloudWatchのストリーミング設定を追加します。
option_settings:
aws:elasticbeanstalk:cloudwatch:logs:
StreamLogs: true
DeleteOnTerminate: false
RetentionInDays: 180
デプロイ後、画像のように設定が反映されました。
プラットフォームがNode.jsの場合、以下のロググループが生成されます。
/aws/elasticbeanstalk/eb-testapp-dev/var/log/nodejs/nodejs.log
/aws/elasticbeanstalk/eb-testapp-dev/var/log/nginx/error.log
/aws/elasticbeanstalk/eb-testapp-dev/var/log/nginx/access.log
/aws/elasticbeanstalk/eb-testapp-dev/var/log/httpd/error_log
/aws/elasticbeanstalk/eb-testapp-dev/var/log/httpd/access_log
/aws/elasticbeanstalk/eb-testapp-dev/var/log/eb-activity.log
eb terminate
( 環境の削除 )
eb terminate
で作成した環境を削除します。EC2
Load Balancer
など削除されます。
$ eb terminate
The environment "eb-testapp-dev" and all associated instances will be terminated.
To confirm, type the environment name: eb-testapp-dev
2019-03-31 06:33:12 INFO terminateEnvironment is starting.
2019-03-31 06:33:30 INFO Deleted CloudWatch alarm named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 06:33:30 INFO Deleted Load Balancer listener named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 06:33:30 INFO Deleted CloudWatch alarm named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 06:33:30 INFO Deleted Auto Scaling group policy named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 06:33:30 INFO Deleted load balancer named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 06:33:30 INFO Deleted Auto Scaling group policy named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 06:33:30 INFO Waiting for EC2 instances to terminate. This may take a few minutes.
2019-03-31 06:35:02 INFO Deleted Auto Scaling group named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 06:35:02 INFO Deleted target group named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 06:35:03 INFO Deleted Auto Scaling launch configuration named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 06:35:18 INFO Deleted security group named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 06:35:49 INFO Deleted security group named: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2019-03-31 06:35:53 INFO Deleting SNS topic for environment eb-testapp-dev.
2019-03-31 06:35:54 INFO terminateEnvironment completed successfully.