この2つを参考に、ECSを動かしてみた
docs.aws.amazon.com
docs.aws.amazon.com
ゴール
Hello World と書かれた index.html を持つ apache サーバをECSで動作させて、ブラウザで動作確認する
手順
- DockerImageを作る
- DockerImageをECRに登録する
- Task DefinitionをECSに登録する
- Taskを実行するClusterを作成する
- Cluster上でTaskを起動する
DockerImageを作る
以下の Dockerfile を作成する
FROM ubuntu:12.04
# Install dependencies
RUN apt-get update -y
RUN apt-get install -y apache2
# Install apache and write hello world message
RUN echo "Hello World!" > /var/www/index.html
# Configure apache
RUN a2enmod rewrite
RUN chown -R www-data:www-data /var/www
ENV APACHE_RUN_USER www-data
ENV APACHE_RUN_GROUP www-data
ENV APACHE_LOG_DIR /var/log/apache2
EXPOSE 80
CMD ["/usr/sbin/apache2", "-D", "FOREGROUND"]
Imageを作成
$ docker build -t hello-world .
動作確認
$ docker run -p 80:80 hello-world
DockerImageをECRに登録する
ECSから使用するImageを参照できるように、レジストリに登録する必要がある
リポジトリの作成
$ aws ecr create-repository --repository-name hello-world
戻り値
{
"repository": {
"repositoryUri": "${registryId}.dkr.ecr.us-east-1.amazonaws.com/hello-world",
"repositoryName": "hello-world",
"createdAt": 1521868901.0,
"repositoryArn": "arn:aws:ecr:us-east-1:${registryId}:repository/hello-world",
"registryId": "${registryId}"
}
}
Imageにタグをつける
$ docker tag hello-world ${AWS_ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com/hello-world
タグとは
- Gitのタグと近い概念
- Imageに複数のタグが登録できる
7.7
とか 7.7.4-alpine
とかバージョンやディストリビューション毎にタグを付けて管理することが多い
上記のコマンドの場合、タグ名を指定していないので、latest
タグが付く
タグ名を付けたい場合は、image名の後ろに :TAGNAME
を付ける
ECRにImageをpushする
dockerコマンドからECRにログインするためのコマンドを生成させる
$ aws ecr get-login --no-include-email
標準出力に出てきたコマンドを実行して、ECRにログインする
$ docker login -u AWS -p ******** https://${AWS_ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com
ECRにImageをpushする
$ docker push ${AWS_ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com/hello-world
Task DefinitionをECSに登録する
Task Definitionを作成
{
"family": "hello-world",
"containerDefinitions": [
{
"name": "hello-world",
"image": "${AWS_ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com/hello-world",
"cpu": 10,
"memory": 500,
"portMappings": [
{
"containerPort": 80,
"hostPort": 80
}
],
"entryPoint": [
"/usr/sbin/apache2",
"-D",
"FOREGROUND"
],
"essential": true
}
]
}
Task DefinitionをECSに登録する
$ aws ecs register-task-definition --cli-input-json file://hello-world-task-def.json
Taskを実行するClusterを作成する
AWSコンソールから作ると色々必要なものを自動で作ってくれるらしい
AWS Fargate でも良いが、まずはEC2インスタンスを使ったクラスタを理解したいので「EC2 Linux+ネットワーキング」を選択
必要な項目を入力後、Cluster、VPC、サブネット、IAMポリシー、オートスケーリンググループ等、必要なものが自動的に作成された
Cluster上でTaskを起動する
aws ecs run-task
でタスクを起動できる
$ aws ecs run-task --task-definition hello-world --cluster test
AWSコンソールでTaskが起動していることを確認
インスタンスのURLにアクセスすると、Hello World が表示されている!
ひとまずここまで
今後理解したいこと
- Service(今回はタスクしか使わなかった)
- オートスケーリンググループ
- ロードバランシング
- 複数のコンテナで同じタスクを起動した場合、どのようにロードバランシングされるのか?
- AWS Fargate