How does automatic target registering happen in EC2 Target Groups for ECS Tasks?

Viewed 2656

I have an ECS Cluster with an ECS Service (Fargate) that specifies a Service Discovery Endpoint. I also have a Cloud Map Service setup with a domain and service name that matches the Service Discovery details entered for the ECS Service. Finally, there is an Application Load Balancer with a Target Group setup for IP targets and initially has no Registered Targets (see full details below).

When I start a Task for the above ECS Service, the Task is automatically registered in the 'Registered Targets' for Target Group described above.

My question is how does AWS know that I want the Tasks from the ECS Service to be automatically added to my ALB's Target Group? I don't see anything in the Target Group that connects it to the ECS Service or to the Cloud Map Service? Is there some other configuration that's achieving this?

What I am trying to do is create a new ALB with a new Target Group and I would like to route traffic from this ALB to the same ECS Service, however this does not enjoy the automatically addition of the ECS Tasks to Registered Targets for the Target Group. Is this possible to achieve?

ECS Cluster: MyCluster

ECS Service (Fargate): 
Name: MyService
Service Discovery endpoint name: namespace.service-discovery-name

Application Load Balancer: 
Name: my-alb
Listener: port 443 (SSL)
Rules: (1) if host = test.domain.com then forward to 'my-target-group'
(2)...

Target Group:
Name: my-target-group
Type: IP
Targets: (initially no registered targets specified. Eventually when a task is started for the above ECS Service a target is automatically registered here.)

Cloud Map:
Domain Name: namespace
Service Name: service-discovery-name
DNS Routing Policy: Multivalue answer routing
Record Type: A

Route 53:
Domain: namespace (Cloud Map Records)
Domain: 
   Name: mydomain.com
   Record: task.mydomain.com -> ALB configured above
1 Answers

This is actually defined and managed within the ECS service when you create it, this service will ensure that the hosts that are created as part of the service will be assigned to the target group of your service.

Looking at the documentation there does not appear to be anyway to replace the target group, in fact looking at the CloudFormation documentation for load balancers it appears that any change would replace the service.

Therefore to apply the service to the new load balancer you would need to create a new service, you can of course use the same task definition though which significantly reduces the amount of work to do. This new service would use your new target group instead.

Related