1. Answers
  2. Setting CPU Alerts for an ECS Service

How do I set CPU alerts for an ECS service?

When you’re managing an ECS service, it’s crucial to monitor resource utilization to maintain performance and handle issues before they become critical. You can achieve this by setting up CPU utilization alerts using CloudWatch. In this guide, you’ll see how to define such alerts.

First, you’ll need to create an ECS cluster and service. Then you’ll define a CloudWatch metric alarm to trigger when CPU utilization exceeds a certain threshold.

Here’s an example:

import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

// ECS Cluster
const example = new aws.ecs.Cluster("example", {name: "example-cluster"});
// ECS Task Definition
const exampleTaskDefinition = new aws.ecs.TaskDefinition("example", {
    family: "example-task",
    containerDefinitions: JSON.stringify([{
        name: "example",
        image: "nginx",
        cpu: 256,
        memory: 512,
        essential: true,
    }]),
});
// ECS Service
const exampleService = new aws.ecs.Service("example", {
    name: "example-service",
    cluster: example.id,
    taskDefinition: exampleTaskDefinition.arn,
    desiredCount: 1,
});
// CloudWatch Alarm for ECS Service CPU utilization
const cpuHigh = new aws.cloudwatch.MetricAlarm("cpu_high", {
    name: "example-service-cpu-high",
    comparisonOperator: "GreaterThanThreshold",
    evaluationPeriods: 1,
    metricName: "CPUUtilization",
    namespace: "AWS/ECS",
    period: 300,
    statistic: "Average",
    threshold: 80,
    alarmDescription: "This alarm triggers if CPU utilization exceeds 80%.",
    dimensions: {
        ClusterName: example.name,
        ServiceName: exampleService.name,
    },
    alarmActions: [],
});
export const clusterName = example.name;
export const serviceName = exampleService.name;
export const cpuAlarmName = cpuHigh.name;

In this example, we created an ECS cluster and a task definition with a simple Nginx container. The ECS service runs one instance of this task. For monitoring, a CloudWatch alarm is configured to trigger when the average CPU utilization exceeds 80% over a period of 5 minutes.

The outputs provide the names of the created ECS cluster, service, and CloudWatch alarm, which can be useful for further references or for integration with other tools.

In summary, you’ve set up a CloudWatch alarm that monitors CPU usage for an ECS service, ensuring you’re alerted when the CPU usage is too high, helping maintain the smooth operation of your application.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up