Automa(tic|g)ally registering ECS task in your AWS Application Load Balancer

2 min read

437 words

Hey there, 👋! I needed to set up automatic registration of ECS tasks of a service in our load balancer. The previous setups were done by colleagues, but now I had the chance to do it myself. Since we're setting up everything via Terraform as Infrastructure as Code, the example below will be written in hcl, the format that Terraform uses to set up resources.

The Magic 🧙 Link: ECS Service and ALB

The key to getting your ECS tasks to automatically register with your ALB lies in the load_balancer block within your aws_ecs_service resource. This little block of code is where the magic happens. Let's break it down:

resource "aws_ecs_service" "my_service" {
  name = "my-service"
  cluster = aws_ecs_cluster.cluster.id
  task_definition = aws_ecs_task_definition.my_task.arn
  desired_count = 1
  launch_type = "FARGATE"

  network_configuration {
    subnets = data.aws_subnets.private.ids
    assign_public_ip = false
    security_groups = [aws_security_group.ecs_tasks.id]
  }

  # This is the interesting part
  load_balancer {
    target_group_arn = aws_lb_target_group.service_tg.arn
    container_name = "my-container"
    container_port = 80
  }
}

Let's break down this `load_balancer' block:

  1. target_group_arn: This points to the ARN of the target group of your ALB.

  2. container_name: This must be the name of the container in your task definition that you want to receive traffic from. For example "app".

  3. container_port: This is the port that your container is listening on.

What happens behind the scenes

When you apply this configuration, ECS and the ALB work together (🤝) to automatically manage task registration. Here's what happens:

  1. When a new ECS task is started, ECS notices the `load_balancer' configuration.
  2. ECS automatically registers the task's IP and port within the specified target group.
  3. The ALB starts sending traffic to the new task as soon as it passes the health checks.
  4. When a task stops or becomes unhealthy, ECS automatically deregisters it from the target group and starts a new one.

It's like having a super-efficient manager for your application, always keeping track of which tasks are ready for traffic!

Wrap things up

Here we go, you don't have to manually keep track of the IPs of our tasks in a target group (I mean, it's 2024). Therefore, we have an easy way of scaling our application plus keep it more resilient when experiencing more traffic as an example.

Remember, the beauty of using Terraform for this setup is that you can easily replicate it across different environments or projects. Just change a few variables and you're good to go!

Thanks for reading, and see you next time! 🚀,

Niklas