AWS ECS Fargate 無伺服器容器服務

AWS ECS Fargate Serverless Container Service

Fargate 概述

AWS Fargate 是一種無伺服器運算引擎,專為容器設計。使用 Fargate,您無需佈建、配置或擴展虛擬機器叢集即可運行容器。Fargate 與 Amazon ECS 和 Amazon EKS 整合,讓您專注於建構應用程式,而非管理基礎設施。

Fargate 的主要優勢

  • 無伺服器架構:無需管理 EC2 實例,AWS 自動處理底層基礎設施
  • 按需付費:僅為容器實際使用的 vCPU 和記憶體資源付費
  • 安全隔離:每個任務在獨立的運算環境中運行,提供工作負載隔離
  • 快速啟動:無需等待 EC2 實例啟動,容器可快速部署
  • 自動擴展:根據應用程式需求自動擴展,無需管理容量

EC2 啟動類型 vs Fargate

選擇正確的啟動類型對於優化成本和效能至關重要。以下是兩種啟動類型的詳細比較:

EC2 啟動類型特點

1
2
3
4
# EC2 啟動類型需要先建立 EC2 容量提供者
aws ecs create-capacity-provider \
  --name my-ec2-capacity-provider \
  --auto-scaling-group-provider autoScalingGroupArn=arn:aws:autoscaling:ap-northeast-1:123456789012:autoScalingGroup:xxx:autoScalingGroupName/my-asg

適用場景:

  • 需要 GPU 或特定硬體支援
  • 大規模且持續運行的工作負載
  • 需要使用 Spot 實例降低成本
  • 需要完全控制底層主機

Fargate 啟動類型特點

1
2
3
4
5
6
7
# Fargate 無需預先配置,直接指定即可
aws ecs create-service \
  --cluster my-cluster \
  --service-name my-fargate-service \
  --launch-type FARGATE \
  --task-definition my-task:1 \
  --desired-count 2

適用場景:

  • 開發和測試環境
  • 批次處理和定時任務
  • 微服務架構
  • 流量變化大的應用程式

比較表

特性EC2 啟動類型Fargate
基礎設施管理使用者負責AWS 全代管
定價模式EC2 實例費用vCPU + 記憶體計費
啟動速度較慢(需等待 EC2)快速(秒級啟動)
GPU 支援支援不支援
Spot 支援支援支援 Fargate Spot
適合工作負載長期運行、大規模短期、突發性

建立 Task Definition

Task Definition 是 Fargate 任務的藍圖,定義容器的所有配置。以下是完整的 Task Definition 範例:

建立 Task Definition JSON 檔案

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
{
  "family": "my-fargate-app",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "512",
  "memory": "1024",
  "executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
  "taskRoleArn": "arn:aws:iam::123456789012:role/ecsTaskRole",
  "containerDefinitions": [
    {
      "name": "web-app",
      "image": "123456789012.dkr.ecr.ap-northeast-1.amazonaws.com/my-app:latest",
      "essential": true,
      "portMappings": [
        {
          "containerPort": 8080,
          "protocol": "tcp"
        }
      ],
      "environment": [
        {
          "name": "NODE_ENV",
          "value": "production"
        }
      ],
      "secrets": [
        {
          "name": "DATABASE_URL",
          "valueFrom": "arn:aws:secretsmanager:ap-northeast-1:123456789012:secret:db-credentials"
        }
      ],
      "healthCheck": {
        "command": ["CMD-SHELL", "curl -f http://localhost:8080/health || exit 1"],
        "interval": 30,
        "timeout": 5,
        "retries": 3,
        "startPeriod": 60
      },
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/my-fargate-app",
          "awslogs-region": "ap-northeast-1",
          "awslogs-stream-prefix": "ecs"
        }
      }
    }
  ]
}

使用 AWS CLI 註冊 Task Definition

1
2
3
4
5
6
7
# 註冊 Task Definition
aws ecs register-task-definition \
  --cli-input-json file://task-definition.json

# 查看已註冊的 Task Definition
aws ecs describe-task-definition \
  --task-definition my-fargate-app:1

設定 CPU 和記憶體

Fargate 的 CPU 和記憶體配置有特定的組合限制。選擇正確的配置對效能和成本都很重要。

有效的 CPU 和記憶體組合

CPU (vCPU)記憶體選項 (GB)
0.250.5, 1, 2
0.51, 2, 3, 4
12, 3, 4, 5, 6, 7, 8
24 - 16 (以 1GB 為單位)
48 - 30 (以 1GB 為單位)
816 - 60 (以 4GB 為單位)
1632 - 120 (以 8GB 為單位)

設定範例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 適用於輕量級服務
aws ecs register-task-definition \
  --family lightweight-service \
  --network-mode awsvpc \
  --requires-compatibilities FARGATE \
  --cpu 256 \
  --memory 512 \
  --container-definitions '[...]'

# 適用於運算密集型服務
aws ecs register-task-definition \
  --family compute-intensive-service \
  --network-mode awsvpc \
  --requires-compatibilities FARGATE \
  --cpu 4096 \
  --memory 8192 \
  --container-definitions '[...]'

建立 ECS Service

Service 負責維護指定數量的任務持續運行,並提供負載平衡和自動恢復功能。

建立基本 Service

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 建立 Fargate Service
aws ecs create-service \
  --cluster my-cluster \
  --service-name my-fargate-service \
  --task-definition my-fargate-app:1 \
  --desired-count 3 \
  --launch-type FARGATE \
  --platform-version LATEST \
  --network-configuration "awsvpcConfiguration={
    subnets=[subnet-0abc123,subnet-0def456],
    securityGroups=[sg-0123456789abcdef0],
    assignPublicIp=ENABLED
  }" \
  --deployment-configuration "maximumPercent=200,minimumHealthyPercent=100"

整合 Application Load Balancer

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 建立與 ALB 整合的 Service
aws ecs create-service \
  --cluster my-cluster \
  --service-name my-web-service \
  --task-definition my-fargate-app:1 \
  --desired-count 3 \
  --launch-type FARGATE \
  --load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:ap-northeast-1:123456789012:targetgroup/my-tg/abc123,containerName=web-app,containerPort=8080" \
  --health-check-grace-period-seconds 60 \
  --network-configuration "awsvpcConfiguration={
    subnets=[subnet-private-1,subnet-private-2],
    securityGroups=[sg-ecs-tasks],
    assignPublicIp=DISABLED
  }"

網路設定(awsvpc 模式)

Fargate 強制使用 awsvpc 網路模式,每個任務都會獲得自己的 Elastic Network Interface(ENI)。

awsvpc 模式特點

  • 每個任務擁有獨立的 IP 位址
  • 完整的 VPC 網路功能支援
  • 可套用安全群組控制流量
  • 支援 VPC Flow Logs 進行網路監控

安全群組設定範例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# 建立 ECS 任務專用安全群組
aws ec2 create-security-group \
  --group-name ecs-fargate-sg \
  --description "Security group for Fargate tasks" \
  --vpc-id vpc-0123456789abcdef0

# 允許來自 ALB 的流量
aws ec2 authorize-security-group-ingress \
  --group-id sg-fargate \
  --protocol tcp \
  --port 8080 \
  --source-group sg-alb

# 允許任務存取外部服務
aws ec2 authorize-security-group-egress \
  --group-id sg-fargate \
  --protocol tcp \
  --port 443 \
  --cidr 0.0.0.0/0

私有子網路配置

對於生產環境,建議將 Fargate 任務放在私有子網路中:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
aws ecs create-service \
  --cluster my-cluster \
  --service-name secure-service \
  --task-definition my-fargate-app:1 \
  --desired-count 2 \
  --launch-type FARGATE \
  --network-configuration "awsvpcConfiguration={
    subnets=[subnet-private-1a,subnet-private-1b],
    securityGroups=[sg-fargate-tasks],
    assignPublicIp=DISABLED
  }"

日誌設定(CloudWatch Logs)

正確的日誌配置對於監控和除錯至關重要。

建立 CloudWatch Log Group

1
2
3
4
5
6
7
8
# 建立日誌群組
aws logs create-log-group \
  --log-group-name /ecs/my-fargate-app

# 設定日誌保留期間
aws logs put-retention-policy \
  --log-group-name /ecs/my-fargate-app \
  --retention-in-days 30

Task Definition 中的日誌配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
  "logConfiguration": {
    "logDriver": "awslogs",
    "options": {
      "awslogs-group": "/ecs/my-fargate-app",
      "awslogs-region": "ap-northeast-1",
      "awslogs-stream-prefix": "ecs",
      "awslogs-create-group": "true"
    }
  }
}

查詢日誌

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 使用 AWS CLI 查詢最近的日誌
aws logs filter-log-events \
  --log-group-name /ecs/my-fargate-app \
  --start-time $(date -d '1 hour ago' +%s)000 \
  --filter-pattern "ERROR"

# 使用 CloudWatch Logs Insights 查詢
aws logs start-query \
  --log-group-name /ecs/my-fargate-app \
  --start-time $(date -d '24 hours ago' +%s) \
  --end-time $(date +%s) \
  --query-string 'fields @timestamp, @message | filter @message like /error/i | sort @timestamp desc | limit 50'

成本考量

Fargate 按照 vCPU 和記憶體的使用量計費,了解計費方式有助於成本優化。

計費方式

  • 計費單位:以秒為單位計費(最少 1 分鐘)
  • 費用組成:vCPU 費用 + 記憶體費用
  • 區域差異:不同區域價格略有不同

成本優化策略

  1. 使用 Fargate Spot:可節省最高 70% 的成本
1
2
3
4
5
6
aws ecs create-service \
  --cluster my-cluster \
  --service-name spot-service \
  --capacity-provider-strategy "capacityProvider=FARGATE_SPOT,weight=4,capacityProvider=FARGATE,weight=1" \
  --task-definition my-fargate-app:1 \
  --desired-count 5
  1. 正確調整資源大小:避免過度配置

  2. 使用 Savings Plans:承諾使用量可獲得折扣

  3. 設定自動擴展:根據實際需求調整任務數量

1
2
3
4
5
6
7
# 設定 Application Auto Scaling
aws application-autoscaling register-scalable-target \
  --service-namespace ecs \
  --resource-id service/my-cluster/my-service \
  --scalable-dimension ecs:service:DesiredCount \
  --min-capacity 1 \
  --max-capacity 10

最佳實踐

安全性最佳實踐

  • 使用最小權限原則配置 IAM 角色
  • 將敏感資料存放在 AWS Secrets Manager
  • 使用 VPC 端點存取 AWS 服務,避免流量經過公網
  • 定期更新容器映像檔以修補安全漏洞

可靠性最佳實踐

  • 將任務分散在多個可用區域
  • 配置健康檢查確保服務可用性
  • 設定適當的重試策略和斷路器
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 配置部署斷路器
aws ecs create-service \
  --cluster my-cluster \
  --service-name reliable-service \
  --deployment-configuration '{
    "deploymentCircuitBreaker": {
      "enable": true,
      "rollback": true
    },
    "maximumPercent": 200,
    "minimumHealthyPercent": 100
  }' \
  --task-definition my-fargate-app:1 \
  --desired-count 3

效能最佳實踐

  • 使用適當的 CPU 和記憶體配置
  • 啟用容器層級的資源監控
  • 使用 ECR 存放映像檔以降低拉取延遲

參考資料

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy