AWS Fargate 是一种无服务器计算引擎,可以用于托管 Docker 容器。它可以与 AWS 的容器编排服务 ECS 或批处理服务 Batch 结合使用。
使用 AWS Fargate 与 ECS 相关联时,可以跳过管理 EC2 实例集群的复杂性,因为 AWS Fargate 会自动管理 EC2 实例。同时,使用 ECS 可以实现高度可扩展的应用程序,并使部署和升级过程更加简单。以下是一个使用 AWS Fargate 和 ECS 部署 Docker 容器的例子,其中 app 为容器名称,my_vpc 为虚拟私有云名称,my_cluster 为 ECS 集群名称:
resource "aws_ecs_task_definition" "app" {
family = "app"
container_definitions = jsonencode([
{
name = "app"
image = "nginx:latest"
portMappings = [
{
containerPort = 80
hostPort = 80
},
]
memoryReservation = 256
cpu = 256
},
])
}
resource "aws_ecs_service" "app" {
name = "app"
cluster = "my_cluster"
desired_count = 2
task_definition = aws_ecs_task_definition.app.arn
launch_type = "FARGATE"
network_configuration {
security_groups = [aws_security_group.app.id]
subnets = aws_subnet.public.*.id
assign_public_ip = true
}
load_balancer {
target_group_arn = aws_lb_target_group.app.arn
container_name = "app"
container_port = "80"
}
}
resource "aws_security_group" "app" {
name_prefix = "app"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_lb_target_group" "app" {
port = 80
protocol = "HTTP"
vpc_id = "my_vpc"
health_check {
path = "/healthcheck"
matcher = "200-299"
}
}
resource "aws_lb_listener" "app" {
load_balancer_arn = aws_lb.app.arn
port = "80