This article is intended to be a quick and dirty snippet for anyone going to through the struggle of getting your ECS service, which might have one or more containers running the same App (being part of an Auto Scaling Group), with a Network Load Balancer (instead of the more common ELB or ALB).
ECS Service/Task Definition
Another particularity of this implementation is that I also decided to use the ECS task’s network mode as awsvpc. In the case that you are not acquainted with this new option, this means that:
- Your container will get its own network interface and its own IP address;
- The Host port and the Container port need to be the same, since there is not middleware managing port match between the two entities.
The cherry on top is that the ECS Service now has the option of automatically registering and deregistering LB targets by their IP address, which fits perfectly on the intention described.
Network Load Balancer
This post isn’t concretely about describing the technical details of what is a Network Load Balancer but about the caveats of using it in this scenario: because NLB is a layer 4 load balancer, you won’t be able to define Security Groups at the NLB level. Instead, you’ll have to make sure you make your tasks/containers secure by attaching the security groups to them – remember that with the awsvpc network mode, each container will get its own NIC.
As for the actual code snippet to support what I’m trying to achieve:
If you are familiar with Terraform and AWS services, the noteworthy parts part of the above code are:
- The aws_lb is of type “network”
- The host port and the container port are the same in the task definition
- awsvpc in the network mode of the tak
- We make the ECS service responsible for registering targets with the “load_balancer” section.
- The target_type of the target group must be of type IP.
- The security group to take into consideration here would be directly in the security_groups section of the aws_ecs_service.
And… that’s it!