ECS 與 EKS

🔥 Vibe Prompt

「在 ECS Fargate 上部署容器化 API 並搭配 CI/CD。與 EKS 比較。」

ECS Fargate(無伺服器容器)

resource "aws_ecs_cluster" "main" {
  name = "app-cluster"
}

resource "aws_ecs_task_definition" "api" {
  family = "api"
  network_mode = "awsvpc"
  requires_compatibilities = ["FARGATE"]
  cpu = "256"
  memory = "512"
  
  container_definitions = jsonencode([{
    name = "api"
    image = "${aws_ecr_repository.api.repository_url}:latest"
    portMappings = [{ containerPort = 8000 }]
    environment = [{ name = "DB_HOST", value = aws_db_instance.postgres.address }]
    logConfiguration = {
      logDriver = "awslogs"
      options = { "awslogs-group" = "/ecs/api", "awslogs-region" = "us-west-2" }
    }
  }])
}

resource "aws_ecs_service" "api" {
  name = "api-service"
  cluster = aws_ecs_cluster.main.id
  task_definition = aws_ecs_task_definition.api.arn
  desired_count = 3
  launch_type = "FARGATE"
  
  network_configuration {
    subnets = aws_subnet.private[*].id
    security_groups = [aws_security_group.app.id]
  }
  
  load_balancer {
    target_group_arn = aws_lb_target_group.api.arn
    container_name = "api"
    container_port = 8000
  }
}

ECS vs EKS 比較

| 面向 | ECS | EKS | |------|-----|-----| | 複雜度 | 低 | 高 | | 靈活性 | AWS 原生 | 多雲 | | 生態系 | 有限 | 豐富(Helm, Istio) | | 費用 | 無控制平面費用 | $0.10/hr 控制平面 | | 適用場景 | AWS-only、簡單應用 | 複雜、多雲 K8s |

CI/CD 管線

# 建置推送到 ECR,然後更新 ECS 服務
- name: Deploy to ECS
  run: |
    aws ecr get-login-password | docker login --username AWS --password-stdin $ECR
    docker build -t $ECR/api:latest .
    docker push $ECR/api:latest
    aws ecs update-service --cluster app-cluster --service api-service --force-new-deployment

最佳實踐

  • 使用 Fargate(無需管理伺服器)
  • 適當設定任務記憶體與 CPU
  • 使用 CloudWatch Logs 紀錄日誌
  • 啟用 ECS Exec 進行除錯

本章總結

  • 理解核心概念與原理
  • 掌握實作方法與技巧
  • 熟悉常見問題與解決方案
  • 能夠應用於實際專案

延伸閱讀

  • 官方文件與 API 參考
  • GitHub 開源專案範例
  • 相關技術書籍與課程
  • 社群討論與技術部落格

解鎖完整教學內容

本章為付費內容。加入專案即可解鎖超過 5000 字的深度解析,包含 10 個以上神級 Prompt 與真實 Source Code 範例!