Amazon Elastic Container Service (Amazon ECS) with the AWS Fargate launch type is a powerful, cloud native, container service that allows customers to create container-based workloads in a matter of minutes without managing the underlying infrastructure. Even with the serverless offering in Fargate, there are still areas you can review to improve cost optimization for running workloads.
For lower level environments, such as test or development, it might not make sense to have tasks running all the time. Setting up a schedule for when tasks should be running or stopped can be as easy way to optimize for cost. For example, if there are no teams working on an application during off-business hours, then having an automated schedule in place to ensure tasks are stopped would be extremely effective.
An easy way to get started with implementing a scheduled for ECS services would be to leverage the schedule scaling configuration for the ECS Fargate service. This would allow you to scale down the service during off hours and scale it back up when developers are working and interacting with the service.
In this post, we will cover how to schedule stop and start ECS Fargate service using by getting advantage of the Application Auto Scaling feature to save costs.
Since we are in love with Terraform, we created a module to do the job.
.... variable "enviornment" { default = "dev" } resource "aws_ecs_cluster" "ecs_service" { ... } resource "aws_ecs_service" "example" { ... } .... module "ecs-autoscaling" { source = "git::https://github.com/faudeltn/ecs-autoscaling.git?ref=v0.1.0" create = var.environment == "dev" ? false : true cluster_name = aws_ecs_cluster.example.name service_name = aws_ecs_service.example.name timezone = "Europe/Rome" scale_out_action = { name = "${aws_ecs_service.example.name}-scale-out" schedule = "cron(00 07 ? * MON-FRI *)" # from Monday to Friday at 7 am min_capacity = 1 max_capacity = 1 } scale_in_action = { name = "${aws_ecs_service.example.name}-scale-in" schedule = "cron(00 19 ? * MON-FRI *)" # from Monday to Friday at at 7 pm min_capacity = 0 max_capacity = 0 } }
In our case if the environment is dev, we put in place 2 automated scheduled actions, one to scale out the service from Monday to Friday at 7 am and another one to scale down the service from Monday to Friday at 7 pm.
Summary
In this tutorial, we showed how to schedule an auto stop and start of our ECS tasks to cut 70% of the costs of our application in the development environment.
If you want to know how we put in place an automated scheduled stop and starts for the RDS Instance check this link.