LoginSignup
0
0

More than 5 years have passed since last update.

ECSでサービスのスケジューリングを行う方法

Last updated at Posted at 2019-02-21

概要

ある特定の時間のみに利用するwebアプリを、出来るだけ低コストで提供したいという背景があり、ECS(Fargate) + Aurora Serverless で構築していた。

Aurora Serverless は、アクセスがなくなると自動で停止されるが、ECSでも同様のことがやりたかったので考えてみた。

前提

ECS のタスク実行には二種類ある。

  • タスクのスケジューリング
  • サービス

タスクのスケジューリングでは、タスク(アプリ)のみが管理される。
サービスでは、LBやtarget groupの設定も管理される。

方法

今回の対象アプリは、バッチアプリではなくwebアプリであり、target groupへの追加部分なども要件に含まれている。
そのため、タスクのスケジューリングは利用できず、自前でlambdaを作ることにした。

serverless frameworkを利用して、lambda + CloudWatch Eventsの構成。

handler.js

タスク数desiredCountを変更し、起動/停止を行う。

const AWS = require('aws-sdk');
const ecs = new AWS.ECS({apiVersion:'2014-11-13',region:'us-east-1'});

module.exports.start = (event, context) => {
  const params = {
      cluster: "CLUSTER_NAME",
      desiredCount: 1,
      service: 'SERVICE_NAME'
  };

  ecs.updateService(params, (err, data) => {
     if (err) console.log(err);
     else console.log(data);
  });
};

module.exports.stop = (event, context) => {
  const params = {
      cluster: "CLUSTER_NAME",
      desiredCount: 0,
      service: 'SERVICE_NAME'
  };

  ecs.updateService(params, (err, data) => {
     if (err) console.log(err);
     else console.log(data);
  });
};

serverless.yml

月曜から金曜の午前9 - 10時のみ稼働させるCloudWatch Eventsの設定

...

functions:
  startEcsService:
    handler: handler.start
    events:
        - schedule: cron(0 0 ? * MON-FRI *)
  stopEcsService:
    handler: handler.stop
    events:
        - schedule: cron(0 1 ? * MON-FRI *)

...

まとめ

LBの設定(target groupへの登録)なども行う場合は、タスクスケジューリングは要件にあわなさそう。
lambdaからAWS SDKで、ECSの操作ができるのでそれを活用した。

0
0
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
0
0