1. Pengenalan AWS ECS
Amazon Elastic Container Service (ECS) adalah layanan container orchestration yang dikelola sepenuhnya oleh AWS. ECS memungkinkan developer untuk menjalankan, mengelola, dan menskalakan aplikasi berbasis container (Docker) tanpa perlu menginstal atau mengelola software orchestration seperti Kubernetes.
ECS pertama kali diluncurkan oleh AWS pada tahun 2014 dan telah menjadi salah satu layanan container paling populer di cloud. ECS terintegrasi secara mendalam dengan ekosistem AWS lainnya seperti IAM, VPC, CloudWatch, Elastic Load Balancing, dan lainnya, menjadikannya pilihan yang sangat kuat untuk workload production.
Mengapa Menggunakan ECS?
| Keunggulan | Penjelasan |
|---|---|
| Fully Managed | AWS mengelola seluruh infrastruktur orchestration β tidak perlu install master node atau etcd |
| Terintegrasi AWS | Native integration dengan IAM, VPC, ALB, CloudWatch, Secrets Manager, ECR |
| Fargate | Serverless compute β tidak perlu mengelola EC2 instance sama sekali |
| Skalabilitas | Auto scaling otomatis berdasarkan CPU, memory, atau custom metrics |
| Keamanan | Task-level IAM roles, network isolation, dan security group per task |
| Biaya | Gratis untuk ECS itu sendiri β bayar hanya untuk compute (EC2/Fargate) |
| Reliability | Tersedia di semua region AWS dengan SLA 99.99% |
ECS vs EKS vs Kubernetes
| Aspek | ECS | EKS | Self-managed K8s |
|---|---|---|---|
| Kompleksitas | π’ Rendah | π‘ Sedang | π΄ Tinggi |
| Vendor Lock-in | π‘ AWS only | π’ Portable | π’ Portable |
| Biaya Management | π’ Gratis | π΄ $0.10/jam/cluster | π΄ Infrastruktur sendiri |
| Ekosistem | π‘ AWS-only | π’ K8s ecosystem | π’ K8s ecosystem |
| Learning Curve | π’ Mudah | π‘ Sedang | π΄ Curam |
| Fitur | π‘ Cukup untuk banyak kasus | π’ Sangat lengkap | π’ Sangat lengkap |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β AWS CLOUD β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β ECS CLUSTER β β β β β β β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β β β β Service A β β Service B β β Service C β β β β β β (Web App) β β (API) β β (Worker) β β β β β β β β β β β β β β β β βββββββββββββ β βββββββββββββ β ββββββ β β β β β β βTaskββTaskββ β βTaskββTaskββ β βTaskβ β β β β β β β A1 ββ A2 ββ β β B1 ββ B2 ββ β β C1 β β β β β β β βββββββββββββ β βββββββββββββ β ββββββ β β β β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β β β β β β β Launch Type: Fargate (serverless) atau EC2 β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β β β ECR β β ALB β β CloudWatchβ β IAM β β β β(Registry)β β (LB) β β(Monitoringβ β(Security)β β β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Jika Anda baru memulai dengan container orchestration di AWS, ECS dengan Fargate adalah pilihan terbaik. Tidak perlu mengelola server, cukup definisikan task dan biarkan AWS yang mengurus sisanya.
2. Arsitektur ECS
Untuk menggunakan ECS secara efektif, Anda harus memahami komponen-komponen utama yang membentuk arsitektur ECS. Setiap komponen memiliki peran spesifik dalam menjalankan dan mengelola container di AWS.
Komponen Utama ECS
1. Cluster β logical grouping dari sumber daya compute (EC2 instances atau Fargate). Cluster adalah "wadah" tempat semua service dan task berjalan.
2. Task Definition β blueprint yang mendefinisikan bagaimana container harus dijalankan. Ini mirip dengan Docker Compose file β berisi informasi image, port, CPU, memory, environment variables, volumes, dan lainnya.
3. Task β instance yang berjalan dari task definition. Satu task bisa berisi satu atau beberapa container yang berjalan bersama (seperti sidecar pattern).
4. Service β memastikan bahwa sejumlah task yang diinginkan selalu berjalan. Service menangani auto scaling, load balancing, dan rolling deployment.
5. Container Agent β software yang berjalan di EC2 instance dan berkomunikasi dengan ECS control plane. Hanya diperlukan pada EC2 launch type.
ECS Launch Types
| Aspek | EC2 Launch Type | Fargate Launch Type |
|---|---|---|
| Server Management | π΄ Anda kelola EC2 | π’ Fully managed |
| Pricing | Bayar per EC2 instance | Bayar per vCPU + memory per detik |
| Control | π’ Penuh atas OS/infra | π‘ Terbatas |
| Bin Packing | π’ Bisa optimasi | π‘ Tidak perlu (auto) |
| GPU Support | π’ Ya | π‘ Terbatas |
| Cold Start | π’ Cepat (sudah running) | π‘ Ada cold start |
| Use Case | Workload besar, konsisten | Workload variabel, burst |
# Install AWS CLI curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" unzip awscliv2.zip sudo ./aws/install # Konfigurasi AWS CLI dengan credentials aws configure # AWS Access Key ID: YOUR_ACCESS_KEY # AWS Secret Access Key: YOUR_SECRET_KEY # Default region name: ap-southeast-1 # Default output format: json # Verifikasi instalasi aws sts get-caller-identity aws ecs list-clusters
3. AWS Fargate
AWS Fargate adalah teknologi serverless compute untuk container yang bekerja dengan ECS (dan EKS). Dengan Fargate, Anda tidak perlu lagi mengelola EC2 instance β cukup definisikan resource yang dibutuhkan container, dan Fargate akan menyediakan compute yang tepat secara otomatis.
Cara Kerja Fargate
Fargate menghilangkan kebutuhan untuk memilih tipe instance, mengelola cluster capacity, atau mengoptimalkan bin packing. Setiap task yang dijalankan di Fargate mendapatkan environment terisolasi sendiri β tidak ada sharing kernel antar task seperti pada EC2 launch type.
EC2 LAUNCH TYPE FARGATE LAUNCH TYPE
βββββββββββββββββββββββ βββββββββββββββββββββββ
β EC2 Instance 1 β β Fargate Task 1 β
β βββββββ βββββββ β β βββββββββββββββββ β
β βTask1β βTask2β β β β Container β β
β βββββββ βββββββ β β β (isolated) β β
β Agent + OS β β βββββββββββββββββ β
βββββββββββββββββββββββ βββββββββββββββββββββββ
βββββββββββββββββββββββ βββββββββββββββββββββββ
β EC2 Instance 2 β β Fargate Task 2 β
β βββββββ βββββββ β β βββββββββββββββββ β
β βTask3β βTask4β β β β Container β β
β βββββββ βββββββ β β β (isolated) β β
β Agent + OS β β βββββββββββββββββ β
βββββββββββββββββββββββ βββββββββββββββββββββββ
Anda kelola: Anda kelola:
- EC2 instances - Task definitions
- Capacity planning - Container code
- OS patching AWS kelola:
- Agent updates - Infrastructure
- Bin packing - OS, runtime
- Scaling
Fargate Pricing (ap-southeast-1)
| Resource | Harga per Jam |
|---|---|
| vCPU | $0.04656 per vCPU per jam |
| Memory | $0.00511 per GB per jam |
Fargate Spot tersedia untuk workload yang bisa toleransi interruption β harganya hingga 70% lebih murah dari Fargate biasa. Cocok untuk batch processing, CI/CD, dan workload non-kritis.
Membuat Cluster Fargate dengan CLI
# Membuat ECS cluster dengan Fargate capacity provider
aws ecs create-cluster \
--cluster-name my-fargate-cluster \
--capacity-providers FARGATE FARGATE_SPOT \
--default-capacity-provider-strategy \
capacityProvider=FARGATE,weight=1 \
capacityProvider=FARGATE_SPOT,weight=1
# Lihat cluster yang sudah dibuat
aws ecs describe-clusters --clusters my-fargate-cluster
# List semua cluster
aws ecs list-clusters
4. Task Definitions
Task Definition adalah blueprint JSON yang mendefinisikan bagaimana container harus dijalankan di ECS. Ini adalah salah satu konsep terpenting dalam ECS β semua yang berjalan di ECS dimulai dari task definition.
Komponen Task Definition
| Komponen | Penjelasan |
|---|---|
| family | Nama task definition, mirip nama image di Docker |
| networkMode | awsvpc (Fargate), bridge, host, none |
| containerDefinitions | Array definisi container (image, port, env, dll) |
| cpu | Unit CPU untuk task (1024 = 1 vCPU) |
| memory | Memory dalam MiB untuk task |
| executionRoleArn | IAM role untuk pulling image & log ke CloudWatch |
| taskRoleArn | IAM role untuk container runtime (akses AWS services) |
| volumes | Volume definitions (EFS, bind mount) |
Contoh Task Definition
{
"family": "web-app",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"executionRoleArn": "arn:aws:iam::123456789:role/ecsTaskExecutionRole",
"taskRoleArn": "arn:aws:iam::123456789:role/ecsTaskRole",
"containerDefinitions": [
{
"name": "web",
"image": "123456789.dkr.ecr.ap-southeast-1.amazonaws.com/web-app:latest",
"portMappings": [
{
"containerPort": 3000,
"hostPort": 3000,
"protocol": "tcp"
}
],
"environment": [
{ "name": "NODE_ENV", "value": "production" },
{ "name": "DB_HOST", "value": "mydb.cluster-xxx.rds.amazonaws.com" }
],
"secrets": [
{
"name": "DB_PASSWORD",
"valueFrom": "arn:aws:secretsmanager:ap-southeast-1:123456789:secret:db-password"
}
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/web-app",
"awslogs-region": "ap-southeast-1",
"awslogs-stream-prefix": "ecs"
}
},
"healthCheck": {
"command": ["CMD-SHELL", "curl -f http://localhost:3000/health || exit 1"],
"interval": 30,
"timeout": 5,
"retries": 3,
"startPeriod": 60
}
}
]
}
Multi-Container Task (Sidecar Pattern)
Satu task bisa menjalankan beberapa container yang berbagi network namespace. Ini berguna untuk pattern seperti sidecar logging, sidecar proxy, atau ambassador pattern.
{
"family": "web-with-sidecar",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "512",
"memory": "1024",
"containerDefinitions": [
{
"name": "app",
"image": "my-app:latest",
"portMappings": [{ "containerPort": 3000 }],
"dependsOn": [
{ "containerName": "envoy", "condition": "START" }
]
},
{
"name": "envoy",
"image": "envoyproxy/envoy:latest",
"portMappings": [
{ "containerPort": 8080 },
{ "containerPort": 9901 }
],
"essential": true
},
{
"name": "log-router",
"image": "amazon/aws-for-fluent-bit:latest",
"essential": true,
"firelensConfiguration": {
"type": "fluentbit"
}
}
]
}
Mendaftarkan Task Definition
# Register task definition dari file JSON aws ecs register-task-definition --cli-input-json file://task-def.json # Register task definition baru (new revision) aws ecs register-task-definition --cli-input-json file://task-def-v2.json # List semua revisi task definition aws ecs list-task-definitions --family-prefix web-app --sort DESC # Deskripsi task definition tertentu aws ecs describe-task-definition --task-definition web-app:3
5. ECS Services
ECS Service memastikan bahwa jumlah task yang diinginkan selalu berjalan dan sehat. Jika sebuah task mati, service akan otomatis menjalankan task baru. Service juga menangani integrasi dengan load balancer dan deployment strategy.
Service Configuration
| Parameter | Penjelasan |
|---|---|
| desiredCount | Jumlah task yang ingin dijalankan secara simultan |
| launchType | FARGATE atau EC2 |
| loadBalancers | ALB/NLB target group integration |
| deploymentConfiguration | minimumHealthyPercent, maximumPercent |
| networkConfiguration | Subnets, security groups, public IP |
| healthCheckGracePeriod | Waktu tunggu sebelum health check dimulai |
| schedulingStrategy | REPLICA (spread) atau DAEMON (one per instance) |
Membuat Service
# Membuat ECS service dengan Fargate
aws ecs create-service \
--cluster my-fargate-cluster \
--service-name web-service \
--task-definition web-app:1 \
--desired-count 2 \
--launch-type FARGATE \
--network-configuration "awsvpcConfiguration={
subnets=[subnet-0abc123,subnet-0def456],
securityGroups=[sg-0123abc],
assignPublicIp=ENABLED
}" \
--load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:...,containerName=web,containerPort=3000"
# Update service (misalnya scale ke 4 task)
aws ecs update-service \
--cluster my-fargate-cluster \
--service-name web-service \
--desired-count 4
# Update service dengan task definition baru (rolling deployment)
aws ecs update-service \
--cluster my-fargate-cluster \
--service-name web-service \
--task-definition web-app:2 \
--force-new-deployment
Service Events & Debugging
# Lihat service events (berguna untuk debugging) aws ecs describe-services \ --cluster my-fargate-cluster \ --services web-service \ --query 'services[0].events[:10]' # List task yang berjalan di service aws ecs list-tasks \ --cluster my-fargate-cluster \ --service-name web-service # Lihat detail task aws ecs describe-tasks \ --cluster my-fargate-cluster \ --tasks <task-arn> # Lihat log container di CloudWatch aws logs get-log-events \ --log-group-name /ecs/web-app \ --log-stream-name ecs/web/<task-id>
Selalu pastikan health check grace period cukup lama untuk aplikasi yang membutuhkan waktu startup panjang. Jika terlalu singkat, service akan menganggap task sebagai unhealthy dan terus-restart task baru, menyebabkan deployment loop.
6. ECS Clusters
ECS Cluster adalah logical grouping yang mengelola sumber daya compute tempat task dan service berjalan. Cluster bisa menggunakan Fargate, EC2, atau kombinasi keduanya (mixed capacity provider).
Cluster Types
Fargate Cluster β cluster kosong tanpa EC2 instances. Semua compute disediakan oleh Fargate secara otomatis. Ini adalah opsi paling simpel.
EC2 Cluster β cluster dengan EC2 instances yang Anda kelola. Anda bertanggung jawab memilih tipe instance, mengelola capacity, dan melakukan patching.
External Cluster (ECS Anywhere) β cluster yang bisa menjalankan task di infrastruktur non-AWS seperti on-premise server atau edge location. Membutuhkan SSM agent dan ECS Anywhere agent.
Capacity Providers
# Membuat cluster dengan EC2 capacity provider
aws ecs create-cluster \
--cluster-name my-ec2-cluster \
--capacity-providers EC2_MY_ASG \
--default-capacity-provider-strategy \
capacityProvider=EC2_MY_ASG,weight=1
# Mengaitkan Auto Scaling Group dengan capacity provider
aws ecs put-cluster-capacity-providers \
--cluster my-ec2-cluster \
--capacity-providers FARGATE FARGATE_SPOT EC2_MY_ASG \
--default-capacity-provider-strategy \
capacityProvider=FARGATE,weight=1 \
capacityProvider=FARGATE_SPOT,weight=2
# Menghapus cluster
aws ecs delete-cluster --cluster my-fargate-cluster
# Mengaktifkan Container Insights untuk monitoring
aws ecs update-cluster-settings \
--cluster my-fargate-cluster \
--settings name=containerInsights,value=enabled
VPC & Networking
Setiap task di Fargate mendapatkan ENI (Elastic Network Interface) sendiri dengan IP address pribadi. Pastikan subnet yang dipilih memiliki cukup IP address untuk jumlah task yang direncanakan.
ββββββββββββββββββββ VPC 10.0.0.0/16 ββββββββββββββββββββ β β β βββ Public Subnet A βββ βββ Public Subnet B βββ β β β 10.0.1.0/24 β β 10.0.2.0/24 β β β β β β β β β β ββββββββ ββββββββ β β ββββββββ β β β β β ALB β βNAT GWβ β β β ALB β β β β β β ENI β β ENI β β β β ENI β β β β β ββββββββ ββββββββ β β ββββββββ β β β βββββββββββββββββββββββ βββββββββββββββββββββββ β β β β βββ Private Subnet A ββ βββ Private Subnet B ββ β β β 10.0.10.0/24 β β 10.0.20.0/24 β β β β β β β β β β ββββββββ ββββββββ β β ββββββββ ββββββββ β β β β βTask 1β βTask 2β β β βTask 3β βTask 4β β β β β β ENI β β ENI β β β β ENI β β ENI β β β β β ββββββββ ββββββββ β β ββββββββ ββββββββ β β β βββββββββββββββββββββββ βββββββββββββββββββββββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
7. Load Balancing & Service Discovery
ECS terintegrasi secara native dengan Application Load Balancer (ALB) dan Network Load Balancer (NLB) untuk mendistribusikan traffic ke container. Selain itu, AWS Cloud Map menyediakan service discovery untuk komunikasi antar service.
ALB Integration
# Membuat Application Load Balancer aws elbv2 create-load-balancer \ --name my-ecs-alb \ --subnets subnet-0abc123 subnet-0def456 \ --security-groups sg-0123abc \ --scheme internet-facing \ --type application # Membuat target group untuk ECS service aws elbv2 create-target-group \ --name my-ecs-tg \ --protocol HTTP \ --port 3000 \ --target-type ip \ --vpc-id vpc-0abc123 \ --health-check-path /health \ --health-check-interval-seconds 30 \ --healthy-threshold-count 2 \ --unhealthy-threshold-count 3 # Membuat listener aws elbv2 create-listener \ --load-balancer-arn <alb-arn> \ --protocol HTTP \ --port 80 \ --default-actions Type=forward,TargetGroupArn=<tg-arn>
Path-based Routing
ALB mendukung path-based routing β Anda bisa mengarahkan traffic ke service yang berbeda berdasarkan URL path. Ini sangat berguna untuk microservices architecture.
# Route /api/* ke API service aws elbv2 create-rule \ --listener-arn <listener-arn> \ --priority 10 \ --conditions Field=path-pattern,Values='/api/*' \ --actions Type=forward,TargetGroupArn=<api-tg-arn> # Route /auth/* ke Auth service aws elbv2 create-rule \ --listener-arn <listener-arn> \ --priority 20 \ --conditions Field=path-pattern,Values='/auth/*' \ --actions Type=forward,TargetGroupArn=<auth-tg-arn>
Service Discovery dengan AWS Cloud Map
# Membuat private DNS namespace aws servicediscovery create-private-dns-namespace \ --name my-internal.local \ --vpc vpc-0abc123 # Membuat service dengan service discovery aws ecs create-service \ --cluster my-cluster \ --service-name api-service \ --task-definition api:1 \ --desired-count 2 \ --service-registries "registryArn=<sd-service-arn>,containerName=api,containerPort=3000" # Sekarang service bisa diakses via DNS: # api-service.my-internal.local
8. Auto Scaling
ECS mendukung Service Auto Scaling menggunakan Application Auto Scaling. Anda bisa menambah atau mengurangi jumlah task berdasarkan berbagai metrik seperti CPU utilization, memory utilization, request count, atau custom CloudWatch metrics.
Target Tracking Scaling
# Register scalable target
aws application-autoscaling register-scalable-target \
--service-namespace ecs \
--scalable-dimension ecs:service:DesiredCount \
--resource-id service/my-cluster/web-service \
--min-capacity 2 \
--max-capacity 20
# Target tracking: jaga CPU rata-rata di 60%
aws application-autoscaling put-scaling-policy \
--service-namespace ecs \
--scalable-dimension ecs:service:DesiredCount \
--resource-id service/my-cluster/web-service \
--policy-name cpu-target-tracking \
--policy-type TargetTrackingScaling \
--target-tracking-scaling-policy-configuration '{
"TargetValue": 60.0,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ECSServiceAverageCPUUtilization"
},
"ScaleInCooldown": 300,
"ScaleOutCooldown": 60
}'
Step Scaling (Manual)
# Step scaling: scale out berdasarkan custom metric
aws application-autoscaling put-scaling-policy \
--service-namespace ecs \
--scalable-dimension ecs:service:DesiredCount \
--resource-id service/my-cluster/web-service \
--policy-name request-count-scaling \
--policy-type StepScaling \
--step-scaling-policy-configuration '{
"AdjustmentType": "ChangeInCapacity",
"StepAdjustments": [
{ "MetricIntervalLowerBound": 0, "MetricIntervalUpperBound": 500, "ScalingAdjustment": 1 },
{ "MetricIntervalLowerBound": 500, "MetricIntervalUpperBound": 1000, "ScalingAdjustment": 2 },
{ "MetricIntervalLowerBound": 1000, "ScalingAdjustment": 4 }
],
"Cooldown": 60
}'
Gunakan target tracking scaling untuk sebagian besar use case β lebih mudah dikelola dan AWS secara otomatis menghitung scaling adjustments. Step scaling berguna ketika Anda butuh kontrol lebih presisi atas kapan dan berapa banyak scaling terjadi.
9. Deployment Strategies
ECS mendukung beberapa deployment strategy yang memungkinkan Anda memperbarui aplikasi tanpa downtime. Memahami strategi ini sangat penting untuk production workload.
Rolling Update (Default)
Task baru diluncurkan secara bertahap sambil task lama dihentikan. Dikontrol oleh minimumHealthyPercent dan maximumPercent.
# Rolling update deployment
aws ecs create-service \
--cluster my-cluster \
--service-name web-service \
--task-definition web-app:2 \
--desired-count 4 \
--deployment-configuration '{
"maximumPercent": 200,
"minimumHealthyPercent": 50
}'
# minimumHealthyPercent 50 = minimal 2 task sehat saat deploy
# maximumPercent 200 = maksimal 8 task saat deploy (4 lama + 4 baru)
Blue/Green Deployment (dengan CodeDeploy)
# Blue/Green membutuhkan AWS CodeDeploy
# Konfigurasi di appspec.yml untuk ECS
version: 0.0
Resources:
- TargetService:
Type: AWS::ECS::Service
Properties:
TaskDefinition: "arn:aws:ecs:region:account:task-definition/web-app:2"
LoadBalancerInfo:
ContainerName: "web"
ContainerPort: 3000
# Deployment controller di service
aws ecs create-service \
--cluster my-cluster \
--service-name web-service \
--task-definition web-app:1 \
--desired-count 2 \
--deployment-controller type=CODE_DEPLOY \
--load-balancers "targetGroupArn=...,containerName=web,containerPort=3000"
Perbandingan Deployment Strategy
| Strategy | Downtime | Rollback | Kompleksitas |
|---|---|---|---|
| Rolling Update | π’ Zero | π‘ Otomatis (re-deploy lama) | π’ Rendah |
| Blue/Green | π’ Zero | π’ Instant (traffic switch) | π‘ Sedang |
| External (canary) | π’ Zero | π’ Fine-grained | π΄ Tinggi |
10. Best Practices
Berikut adalah best practices yang direkomendasikan AWS dan praktisi DevOps untuk menggunakan ECS secara efektif dan aman di production:
Security Best Practices
- Task IAM Roles β Gunakan task role (bukan instance role) untuk memberikan permission per-task. Ini prinsip least privilege.
- Secrets Manager β Jangan simpan secrets di environment variables biasa. Gunakan AWS Secrets Manager atau SSM Parameter Store dengan integrasi native ECS.
- Private Subnets β Jalankan task di private subnets. Gunakan NAT Gateway untuk outbound traffic dan ALB untuk inbound.
- Security Groups β Buat security group khusus per service. Jangan gunakan security group yang terlalu terbuka.
- ECR Image Scanning β Aktifkan scanning otomatis di ECR untuk mendeteksi vulnerability di container images.
- Read-only Root Filesystem β Set
readonlyRootFilesystem: truepada container yang tidak perlu menulis ke filesystem.
Performance Best Practices
- Right-sizing β Monitor penggunaan CPU dan memory aktual. Jangan over-provision (buang uang) atau under-provision (throttling/crash).
- Multi-AZ β Deploy task ke minimal 2 Availability Zone untuk high availability.
- Container Insights β Aktifkan Container Insights untuk monitoring detail CPU, memory, network, dan disk per task/service.
- Connection Draining β Konfigurasi deregistration delay di ALB target group untuk graceful shutdown.
- Ephemeral Storage β Fargate menyediakan 20GB ephemeral storage (bisa sampai 200GB). Gunakan untuk temp files, bukan persistent data.
Cost Optimization
- Fargate Spot β Gunakan untuk workload yang toleransi interruption (batch, CI/CD). Hemat hingga 70%.
- Savings Plans β Commit Fargate usage untuk diskon hingga 50%.
- Right-sizing β Sesuaikan CPU/memory task dengan aktual usage. Banyak team over-provision hingga 2-3x.
- Auto Scaling
# Contoh CloudFormation untuk ECS Service lengkap
Resources:
ECSCluster:
Type: AWS::ECS::Cluster
Properties:
ClusterName: production-cluster
ClusterSettings:
- Name: containerInsights
Value: enabled
TaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: web-app
Cpu: '256'
Memory: '512'
NetworkMode: awsvpc
RequiresCompatibilities:
- FARGATE
ExecutionRoleArn: !GetAtt ExecutionRole.Arn
TaskRoleArn: !GetAtt TaskRole.Arn
ContainerDefinitions:
- Name: web
Image: !Sub '${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/web-app:latest'
PortMappings:
- ContainerPort: 3000
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-group: !Ref LogGroup
awslogs-region: !Ref AWS::Region
awslogs-stream-prefix: ecs
ECSService:
Type: AWS::ECS::Service
DependsOn: ALBListener
Properties:
Cluster: !Ref ECSCluster
TaskDefinition: !Ref TaskDefinition
DesiredCount: 2
LaunchType: FARGATE
NetworkConfiguration:
AwsvpcConfiguration:
AssignPublicIp: ENABLED
SecurityGroups:
- !Ref ServiceSecurityGroup
Subnets:
- !Ref PublicSubnetA
- !Ref PublicSubnetB
LoadBalancers:
- ContainerName: web
ContainerPort: 3000
TargetGroupArn: !Ref TargetGroup
Gunakan AWS Copilot CLI untuk mempermudah deployment ECS. Copilot mengotomatisasi pembuatan cluster, service, load balancer, pipeline CI/CD, dan monitoring hanya dengan beberapa command. Cocok untuk developer yang ingin fokus ke kode, bukan infrastruktur.
π Quiz Pemahaman
Uji pemahaman Anda tentang AWS ECS dengan menjawab pertanyaan berikut: