DevOps & Cloud

AWS ECS: Container Service

TOKEN

Panduan lengkap AWS ECS β€” Fargate, task definitions, services, cluster management, load balancing, auto scaling, dan best practices untuk container orchestration di AWS

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 ManagedAWS mengelola seluruh infrastruktur orchestration β€” tidak perlu install master node atau etcd
Terintegrasi AWSNative integration dengan IAM, VPC, ALB, CloudWatch, Secrets Manager, ECR
FargateServerless compute β€” tidak perlu mengelola EC2 instance sama sekali
SkalabilitasAuto scaling otomatis berdasarkan CPU, memory, atau custom metrics
KeamananTask-level IAM roles, network isolation, dan security group per task
BiayaGratis untuk ECS itu sendiri β€” bayar hanya untuk compute (EC2/Fargate)
ReliabilityTersedia 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
Diagram: AWS ECS Architecture Overview
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                      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)β”‚    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
πŸ’‘ Tips

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
PricingBayar per EC2 instanceBayar 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 CaseWorkload besar, konsistenWorkload variabel, burst
Bash
# 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.

Diagram: Fargate vs 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
⚠️ Peringatan

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

Bash
# 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
familyNama task definition, mirip nama image di Docker
networkModeawsvpc (Fargate), bridge, host, none
containerDefinitionsArray definisi container (image, port, env, dll)
cpuUnit CPU untuk task (1024 = 1 vCPU)
memoryMemory dalam MiB untuk task
executionRoleArnIAM role untuk pulling image & log ke CloudWatch
taskRoleArnIAM role untuk container runtime (akses AWS services)
volumesVolume definitions (EFS, bind mount)

Contoh Task Definition

JSON
{
  "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.

JSON
{
  "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

Bash
# 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
desiredCountJumlah task yang ingin dijalankan secara simultan
launchTypeFARGATE atau EC2
loadBalancersALB/NLB target group integration
deploymentConfigurationminimumHealthyPercent, maximumPercent
networkConfigurationSubnets, security groups, public IP
healthCheckGracePeriodWaktu tunggu sebelum health check dimulai
schedulingStrategyREPLICA (spread) atau DAEMON (one per instance)

Membuat Service

Bash
# 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

Bash
# 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>
⚠️ Peringatan

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

Bash
# 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.

Diagram: ECS Networking
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ 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

Bash
# 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.

Bash
# 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

Bash
# 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

Bash
# 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)

Bash
# 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
  }'
πŸ’‘ Tips

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.

Bash
# 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)

Bash
# 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

Performance Best Practices

Cost Optimization

YAML
# 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
πŸ’‘ Tips

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:

Pertanyaan 1: Apa perbedaan utama antara Fargate dan EC2 launch type di ECS?

a) Fargate lebih mahal dari EC2
b) Fargate tidak perlu mengelola server, EC2 membutuhkan pengelolaan instance
c) EC2 tidak mendukung Docker
d) Fargate hanya bisa di satu AZ

Pertanyaan 2: Apa fungsi utama ECS Service?

a) Menyimpan container images
b) Memastikan jumlah task yang diinginkan selalu berjalan
c) Mengelola VPC networking
d) Build Docker images

Pertanyaan 3: Apa itu Task Definition dalam ECS?

a) Instance yang sedang berjalan dari container
b) Cluster tempat task berjalan
c) Blueprint JSON yang mendefinisikan bagaimana container dijalankan
d) Load balancer untuk container

Pertanyaan 4: Deployment strategy apa yang memungkinkan instant rollback?

a) Rolling Update
b) Blue/Green dengan CodeDeploy
c) Re-create deployment
d) Manual restart

Pertanyaan 5: Mengapa disarankan menjalankan task di private subnets?

a) Karena private subnet lebih cepat
b) Untuk keamanan β€” task tidak bisa diakses langsung dari internet
c) Karena Fargate hanya support private subnet
d) Untuk menghemat biaya NAT Gateway
πŸ” Zoom
100%
🎨 Tema