AWS Fargate Docker Container Deploy — คู่มือฉบับสมบูรณ์ 2026
โดย อ.บอม กิตติทัศน์ เจริญพนาสิทธิ์ | อัปเดต 24 ก.พ. 2026 | อ่าน 15 นาที
- AWS Fargate คืออะไร — Serverless Container
- เปรียบเทียบ Fargate vs EC2 vs Lambda vs App Runner
- ECS Concepts — Cluster, Task, Service
- สร้าง Docker Image และ Push ขึ้น ECR
- Task Definition — Blueprint ของ Container
- สร้าง ECS Cluster และ Fargate Service
- Application Load Balancer (ALB)
- Auto Scaling — Scale ตาม Traffic
- Networking — VPC, Security Group, Service Discovery
- Logging และ Monitoring
- CI/CD Pipeline
- Cost Optimization
- Best Practices และสรุป
AWS Fargate คืออะไร — Serverless Container
AWS Fargate เป็น Serverless Compute Engine สำหรับ Container ที่ทำงานร่วมกับ Amazon ECS (Elastic Container Service) และ Amazon EKS (Elastic Kubernetes Service) จุดเด่นคือไม่ต้องจัดการ EC2 Instance เลย ไม่ต้องเลือก Instance Type ไม่ต้อง Patch OS ไม่ต้อง Scale Server AWS จัดการ Infrastructure ทั้งหมดให้ คุณแค่กำหนด CPU/Memory ที่ต้องการ แล้ว Deploy Container Image
Fargate เหมาะกับทีมที่ต้องการ Deploy Container อย่างรวดเร็วโดยไม่ต้องมีความเชี่ยวชาญด้าน Infrastructure ลด Ops Overhead ให้ Developer โฟกัสที่โค้ด ใช้งานโดย Startup จำนวนมากที่ต้องการความเร็วในการ Deploy มากกว่าการ Optimize ค่าใช้จ่ายระดับ Infrastructure
เปรียบเทียบ Fargate vs EC2 vs Lambda vs App Runner
| คุณสมบัติ | Fargate | EC2 Launch Type | Lambda | App Runner |
|---|---|---|---|---|
| Server Management | ไม่ต้อง | ต้องจัดการเอง | ไม่ต้อง | ไม่ต้อง |
| Max Runtime | ไม่จำกัด | ไม่จำกัด | 15 นาที | 120 วินาที/req |
| Startup Time | 30-60 วินาที | นาที (EC2 boot) | มิลลิวินาที-วินาที | วินาที |
| Max vCPU | 16 vCPU | ตาม Instance | 10 GB (6 vCPU) | 4 vCPU |
| Networking | VPC + ENI | VPC + ENI | VPC (optional) | Limited |
| Cost Model | vCPU-hr + GB-hr | EC2 Instance | Request + Duration | vCPU-hr + GB-hr |
| เหมาะกับ | Long-running Service | Cost-optimized | Event-driven | Simple Web/API |
ECS Concepts — Cluster, Task, Service
- Cluster — กลุ่มของ Resource (Fargate หรือ EC2) สำหรับรัน Container คล้ายกับ Kubernetes Cluster
- Task Definition — Blueprint กำหนด Container Image, CPU/Memory, Port, Env Vars, Log Config เหมือน docker-compose.yml
- Task — Instance ที่รันจาก Task Definition หนึ่ง Task มีได้หลาย Container (Sidecar Pattern)
- Service — จัดการ Task ให้มีจำนวนที่กำหนด ถ้า Task ตาย จะสร้างใหม่อัตโนมัติ เชื่อมกับ Load Balancer และ Auto Scaling
สร้าง Docker Image และ Push ขึ้น ECR
# สร้าง ECR Repository
aws ecr create-repository --repository-name my-api --region ap-southeast-1
# Login ECR
aws ecr get-login-password --region ap-southeast-1 | \
docker login --username AWS --password-stdin 123456789.dkr.ecr.ap-southeast-1.amazonaws.com
# Build Image
docker build -t my-api:v1.0 .
# Tag
docker tag my-api:v1.0 123456789.dkr.ecr.ap-southeast-1.amazonaws.com/my-api:v1.0
# Push
docker push 123456789.dkr.ecr.ap-southeast-1.amazonaws.com/my-api:v1.0
Task Definition — Blueprint ของ Container
{
"family": "my-api",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "512",
"memory": "1024",
"executionRoleArn": "arn:aws:iam::123456789:role/ecsTaskExecutionRole",
"taskRoleArn": "arn:aws:iam::123456789:role/ecsTaskRole",
"containerDefinitions": [
{
"name": "api",
"image": "123456789.dkr.ecr.ap-southeast-1.amazonaws.com/my-api:v1.0",
"portMappings": [
{"containerPort": 8080, "protocol": "tcp"}
],
"environment": [
{"name": "NODE_ENV", "value": "production"}
],
"secrets": [
{"name": "DATABASE_URL", "valueFrom": "arn:aws:secretsmanager:ap-southeast-1:123456789:secret:db-url"}
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/my-api",
"awslogs-region": "ap-southeast-1",
"awslogs-stream-prefix": "ecs"
}
},
"healthCheck": {
"command": ["CMD-SHELL", "curl -f http://localhost:8080/health || exit 1"],
"interval": 30,
"timeout": 5,
"retries": 3,
"startPeriod": 60
},
"essential": true
}
]
}
CPU/Memory Combination ที่ Fargate รองรับ ได้แก่ 0.25 vCPU (512MB-2GB), 0.5 vCPU (1-4GB), 1 vCPU (2-8GB), 2 vCPU (4-16GB), 4 vCPU (8-30GB), 8 vCPU (16-60GB) และ 16 vCPU (32-120GB)
สร้าง ECS Cluster และ Fargate Service
# สร้าง Cluster
aws ecs create-cluster --cluster-name production
# Register Task Definition
aws ecs register-task-definition --cli-input-json file://task-definition.json
# สร้าง Service
aws ecs create-service \
--cluster production \
--service-name my-api \
--task-definition my-api:1 \
--desired-count 3 \
--launch-type FARGATE \
--network-configuration '{
"awsvpcConfiguration": {
"subnets": ["subnet-abc123", "subnet-def456"],
"securityGroups": ["sg-12345"],
"assignPublicIp": "DISABLED"
}
}' \
--load-balancers '[{
"targetGroupArn": "arn:aws:elasticloadbalancing:...:targetgroup/my-api-tg/...",
"containerName": "api",
"containerPort": 8080
}]' \
--deployment-configuration '{
"deploymentCircuitBreaker": {"enable": true, "rollback": true},
"maximumPercent": 200,
"minimumHealthyPercent": 100
}'
Application Load Balancer (ALB)
ALB กระจาย Traffic ไปยัง Fargate Task หลายตัว พร้อม Health Check ถ้า Task ไม่ Healthy จะหยุดส่ง Traffic ไปหา สร้าง ALB ด้วย AWS CLI หรือ CloudFormation กำหนด Listener (Port 80/443), Target Group (ECS Service) และ Health Check Path
# สร้าง Target Group แบบ IP (Fargate ใช้ awsvpc)
aws elbv2 create-target-group \
--name my-api-tg \
--protocol HTTP \
--port 8080 \
--vpc-id vpc-12345 \
--target-type ip \
--health-check-path /health \
--health-check-interval-seconds 30 \
--healthy-threshold-count 2 \
--unhealthy-threshold-count 3
Auto Scaling — Scale ตาม Traffic
# ลงทะเบียน Scalable Target
aws application-autoscaling register-scalable-target \
--service-namespace ecs \
--resource-id service/production/my-api \
--scalable-dimension ecs:service:DesiredCount \
--min-capacity 2 \
--max-capacity 20
# Target Tracking — Scale ตาม CPU
aws application-autoscaling put-scaling-policy \
--service-namespace ecs \
--resource-id service/production/my-api \
--scalable-dimension ecs:service:DesiredCount \
--policy-name cpu-scaling \
--policy-type TargetTrackingScaling \
--target-tracking-scaling-policy-configuration '{
"TargetValue": 70.0,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ECSServiceAverageCPUUtilization"
},
"ScaleInCooldown": 300,
"ScaleOutCooldown": 60
}'
# Scale ตาม Request Count ต่อ Target
aws application-autoscaling put-scaling-policy \
--service-namespace ecs \
--resource-id service/production/my-api \
--scalable-dimension ecs:service:DesiredCount \
--policy-name request-scaling \
--policy-type TargetTrackingScaling \
--target-tracking-scaling-policy-configuration '{
"TargetValue": 1000.0,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ALBRequestCountPerTarget",
"ResourceLabel": "app/my-alb/.../targetgroup/my-api-tg/..."
}
}'
Networking — VPC, Security Group, Service Discovery
Fargate Task แต่ละตัวได้ ENI (Elastic Network Interface) ของตัวเอง มี Private IP อยู่ใน VPC ที่กำหนด ควรวาง Task ใน Private Subnet ให้ ALB อยู่ใน Public Subnet รับ Traffic จาก Internet แล้ว Forward ไป Task
สำหรับ Service-to-Service Communication ใช้ AWS Cloud Map (Service Discovery) ให้ Service อื่นเรียกผ่าน DNS Name เช่น my-api.production.local แทน IP Address ที่เปลี่ยนทุกครั้งที่ Task ถูกสร้างใหม่
Logging และ Monitoring
- CloudWatch Logs — Fargate ส่ง Container Log ไป CloudWatch อัตโนมัติ ผ่าน awslogs Log Driver
- CloudWatch Metrics — CPUUtilization, MemoryUtilization, RunningTaskCount
- Container Insights — เปิดเพิ่มเพื่อดู Metrics ระดับ Container (Network, Disk I/O)
- X-Ray — Distributed Tracing ติดตาม Request ข้าม Service
# เปิด Container Insights
aws ecs update-cluster-settings \
--cluster production \
--settings name=containerInsights,value=enabled
CI/CD Pipeline
# GitHub Actions — Build + Deploy to Fargate
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ap-southeast-1
- uses: aws-actions/amazon-ecr-login@v2
id: ecr
- name: Build & Push
run: |
docker build -t ${{ steps.ecr.outputs.registry }}/my-api:${{ github.sha }} .
docker push ${{ steps.ecr.outputs.registry }}/my-api:${{ github.sha }}
- name: Update Task Definition
run: |
TASK_DEF=$(aws ecs describe-task-definition --task-definition my-api --query taskDefinition)
NEW_DEF=$(echo $TASK_DEF | jq --arg IMG "${{ steps.ecr.outputs.registry }}/my-api:${{ github.sha }}" \
'.containerDefinitions[0].image = $IMG | del(.taskDefinitionArn,.revision,.status,.registeredAt,.registeredBy,.requiresAttributes,.compatibilities)')
echo "$NEW_DEF" > new-task-def.json
aws ecs register-task-definition --cli-input-json file://new-task-def.json
- name: Deploy
run: |
aws ecs update-service --cluster production --service my-api --force-new-deployment
Cost Optimization
- Fargate Spot — ลดค่าใช้จ่าย 70% สำหรับ Workload ที่ Interrupt ได้ เช่น Batch Job, Dev/Test
- Savings Plans — Commit ใช้งาน 1-3 ปี ลด 50% สำหรับ Production Workload ที่มั่นคง
- Right-sizing — ดู Metrics จริงแล้วลด CPU/Memory ให้เหมาะสม อย่า Over-provision
- Arm64 (Graviton) — ใช้ Fargate บน Graviton Processor ลดค่าใช้จ่าย 20% พร้อม Performance ที่ดีขึ้น
- Auto Scaling ลงได้ — ตั้ง Scale-in ให้ลดจำนวน Task เมื่อ Traffic ต่ำ
Best Practices และสรุป
- ใช้ Private Subnet — Task ไม่ควร Expose ตรงไป Internet ใช้ ALB เป็น Entry Point
- ใช้ Secrets Manager — เก็บ Credential ใน Secrets Manager อ้างอิงผ่าน Task Definition
- Health Check ต้องมี — ทั้ง Container Health Check และ ALB Health Check
- เปิด Circuit Breaker — ป้องกัน Bad Deployment ด้วย Deployment Circuit Breaker + Auto Rollback
- ใช้ Graviton — ลดค่าใช้จ่ายและเพิ่ม Performance
- Tag Resources — Tag ทุก Resource ด้วย Team, Environment, Cost Center สำหรับ Cost Allocation
- ใช้ Service Connect — แทน Service Discovery แบบเก่า มี Observability ดีกว่า
- Image Scanning — เปิด ECR Image Scanning ตรวจ Vulnerability อัตโนมัติ
AWS Fargate ทำให้ Deploy Container ง่ายมากโดยไม่ต้องจัดการ Server เหมาะกับทีมที่ต้องการ Speed มากกว่า Cost Optimization ระดับ Infrastructure เมื่อรวมกับ ALB, Auto Scaling, CI/CD จะได้ระบบ Production-ready ที่ Scalable และ Reliable ติดตามบทความใหม่ๆ ได้ที่ SiamCafe.net
คำถามที่พบบ่อย (FAQ)
Q: AWS Fargate คืออะไร
Serverless Compute Engine สำหรับ Container ทำงานกับ ECS/EKS ไม่ต้องจัดการ EC2 จ่ายตาม vCPU+Memory ที่ใช้จริง
Q: Fargate ต่างจาก EC2 Launch Type อย่างไร
EC2 ต้องจัดการ Instance เอง (Patch, Scale) ส่วน Fargate AWS จัดการทั้งหมด แลกกับราคาแพงกว่า 20-40%
Q: Task Definition คืออะไร
Blueprint กำหนด Container Image, CPU/Memory, Port, Env Vars, Log Config คล้าย docker-compose.yml สำหรับ ECS
Q: Fargate แพงไหม ลดค่าใช้จ่ายอย่างไร
ใช้ Fargate Spot (ลด 70%), Savings Plans (ลด 50%), Graviton Arm64 (ลด 20%), Right-sizing CPU/Memory
Q: CI/CD ทำอย่างไร
Build Docker → Push ECR → Update Task Definition → Update ECS Service --force-new-deployment → Rolling Update อัตโนมัติ