You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ECS多容器部署问题:仅用单个ALB实现三个依赖容器的连通配置

核心实现逻辑

你不需要为内部服务配置额外ALB,依托ECS本身的网络能力即可实现容器互通,以下是具体实现步骤:

1. 确定部署模式

你可以根据业务需要选以下两种部署模式之一:

  • 模式A:三个容器放在同一份ECS任务定义中
    适合三个容器绑定部署、扩缩容步调一致的场景,直接用awsvpc网络模式,同任务下所有容器共享网络命名空间,直接通过localhost:{容器端口}即可互相调用,和你本地docker-compose的互通逻辑高度相似,仅需要把原docker-compose配置中用服务名调用的部分改成localhost+对应端口即可,几乎不需要修改业务配置:
    • nginx-frontend调用php:直接用localhost:9000(假设php暴露9000端口)
    • nginx-backend调用php:同样用localhost:9000
    • ALB仅需要绑定到nginx-frontend的80/443端口即可,其余容器不需要对外暴露任何端口
  • 模式B:三个容器拆分为独立的ECS服务
    适合需要独立扩缩容不同服务的场景,搭配AWS Cloud Map实现服务发现,调用逻辑和本地docker-compose的服务名调用完全一致,不需要修改业务配置:
    • 给php服务、nginx-backend服务分别注册内部服务域名,比如php.service.local、nginx-backend.service.local
    • 两个nginx容器直接通过内部域名调用对应服务,流量走VPC内部网络,不需要经过公网或ALB
    • ALB仅关联nginx-frontend服务的目标组,其余服务不需要配置对外的监听器或目标组

2. Terraform配置要点

同任务部署的核心配置示例

resource "aws_ecs_task_definition" "app" {
  family                   = "app-stack"
  network_mode             = "awsvpc"
  requires_compatibilities = ["FARGATE"] # 若使用EC2启动模式可对应调整
  cpu                      = "1024"
  memory                   = "2048"
  execution_role_arn       = aws_iam_role.ecs_execution.arn

  container_definitions = jsonencode([
    {
      name      = "php"
      image     = "${aws_ecr_repository.php.repository_url}:latest"
      essential = true
      portMappings = [
        {
          containerPort = 9000
          hostPort      = 9000
        }
      ]
    },
    {
      name      = "nginx-backend"
      image     = "${aws_ecr_repository.nginx_backend.repository_url}:latest"
      essential = true
      portMappings = [
        {
          containerPort = 8080
          hostPort      = 8080
        }
      ]
    },
    {
      name      = "nginx-frontend"
      image     = "${aws_ecr_repository.nginx_frontend.repository_url}:latest"
      essential = true
      portMappings = [
        {
          containerPort = 80
          hostPort      = 80
        }
      ]
    }
  ])
}

# ALB仅关联nginx-frontend的目标组
resource "aws_lb_target_group" "frontend" {
  name     = "frontend-tg"
  port     = 80
  protocol = "HTTP"
  vpc_id   = var.vpc_id
  target_type = "ip"
}

resource "aws_lb_listener" "http" {
  load_balancer_arn = aws_lb.frontend.arn
  port              = "80"
  protocol          = "HTTP"

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.frontend.arn
  }
}

独立服务+服务发现的核心配置要点

  • 先创建Cloud Map私有命名空间
  • 每个内部服务创建服务发现注册配置,关联到对应的ECS服务
  • nginx配置中直接写对应服务的内部域名即可,不需要修改其他逻辑

3. 配置验证

部署完成后可以通过ECS的exec功能进入nginx-frontend容器,用curl或nc命令验证和php、nginx-backend的连通性,确保内部调用链路正常后再对外提供服务。

内容的提问来源于stack exchange,提问作者awiechert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 08:24:04