25
22

More than 5 years have passed since last update.

ecs-cliを使ってFargateで簡単なタスクを実行してみる

Last updated at Posted at 2018-06-23

概要

これの続きから
ecs-cli ベースでイメージを管理する

とりあえずECRにイメージがあがったので、Fargateを使って非常駐のタスクとして実行してみる。
(常駐コンテナ=service, 非常駐コンテナ=run-task というらしい)

手順

ECSクラスタを作成する

ECSクラスタを作る。Fargateを使うので、EC2のインスタンスなどを用意する必要はない。

クラスタの事前設定

まずはクラスタの事前設定を行う

$ ecs-cli configure --cluster hello-world --config-name hello-world --default-launch-type FARGATE --region $AWS_REGION

以下のようなファイルが作成される

~/.ecs/config
version: v1
default: hello-world
clusters:
  hello-world:
    cluster: hello-world
    region: us-east-1
    default_launch_type: FARGATE

複数の設定が保存されるようだが、構成の切り替えをいい感じにやってくれない。(デフォルトに設定されたクラスタが使われる)
direnv でクラスタの設定コマンドが毎回実行されるようにしておく。

ecs-cli configure default --config-name hello-world

クラスタの作成

クラスタを作成する。
一緒に実行環境となるVPC/Subnetも作成されるのでIDをメモしておく。

$ ecs-cli up
INFO[0003] Created cluster                               cluster=hello-world region=us-east-1
INFO[0005] Waiting for your cluster resources to be created...
INFO[0006] Cloudformation stack status                   stackStatus=CREATE_IN_PROGRESS
VPC created: vpc-2a856650
Subnet created: subnet-482d8866
Subnet created: subnet-966806dc
Cluster creation succeeded.

セキュリティグループの作成

タスクの実行に必要なセキュリティグループを作成する。
作成されたIDをメモしておく

$ aws ec2 create-security-group --group-name "hello-world" --description "default security group of hello-world" --vpc-id "vpc-2a856650"
sg-0deb7f46

タスク定義を作成する

ベースのdocker-compose.yml、本番用差分docker-compose.yml、ECS設定用ecs-params.ymlの3ファイルに分割して作成する

docker-compose.yml
version: '2'
services:
  app:
    build: .
    image: 08123xxxx.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest
docker-compose.production.yml
version: '2'
services:
  app:
    logging:
      driver: awslogs
      options:
        awslogs-group: hello-world
        awslogs-region: us-east-1
        awslogs-stream-prefix: hello-world
ecs-params.yml
version: 1
task_definition:
  ecs_network_mode: awsvpc
  task_execution_role: ecsTaskExecutionRole
  task_size:
    cpu_limit: 256
    mem_limit: 512
  services:
    app:
      essential: true

run_params:
  network_configuration:
    awsvpc_configuration:
      subnets:
        - subnet-482d8866
        - subnet-966806dc
      security_groups:
        - sg-0deb7f46
      assign_public_ip: ENABLED

サブネットやセキュリティグループはクラスタ作成に一緒に生成されたものを利用している

タスクを実行する

タスク定義の登録とタスクの実行が同時に行われる
すでに定義済みで設定に更新があった場合、自動で新しいリビジョンが作成される

$ ecs-cli compose --file docker-compose.yml --file docker-compose.production.yml --ecs-params ecs-params.yml up --create-log-groups
25
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
22