Create AWS Fargate Service

Create AWS Fargate Service

  1. Initialize a FargateService within the ProductsServiceStack constructor with the ID ProductsService:
   FargateService fargateService = new FargateService(this, "ProductsService",
       FargateServiceProps.builder()
           .build());

Architect

  1. Set the service name to ProductsService:
   .serviceName("ProductsService")

Architect

  1. Next, specify the cluster that was created earlier to create the Fargate service:
.cluster(productsServiceProps.cluster())

Architect

  1. In addition to the cluster, we need to specify the task definition to use for creating the Fargate service. We will use the fargateTaskDefinition that was created earlier:
   .taskDefinition(fargateTaskDefinition)

Architect

  1. Next, specify the desired number of instances to use. In this workshop, we will use 2 instances:
.desiredCount(2)

Architect

  1. Next, to keep the Fargate tasks in a private subnet and allow outbound connectivity through a NAT Gateway without assigning a public IP:
   .assignPublicIp(false)

Architect

  1. Additionally, if you did not create a NAT Gateway in the VPC creation phase, you can enable public IP assignment for the Fargate service:
   .assignPublicIp(true)

Đừng làm trong môi trường production

Architect

  1. ECS service của chúng ta cần permission để pull image từ ECR repository. Vì vậy chúng ta cần phải cấp quyền như sau
productsServiceProps.repository().grantPull(Objects.requireNonNull(fargateTaskDefinition.getExecutionRole()));

Architect

  1. Finally, another important aspect is defining that our service accepts requests on HTTP port 8081:
fargateService.getConnections().getSecurityGroups().get(0).addIngressRule(Peer.anyIpv4(), Port.tcp(8081));

Architect