☀️Siang
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

Artikel: Aws Ecs Containers Artikel: Aws Ecs Containers


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: Fargate vs EC2 Launch Type
EC2 Instance 1
Task 1
Task 2
/"Agent + OS"/
EC2 Instance 2
Task 3
Task 4
/"Agent + OS"/
Fargate Task 1 Container (isolated) No agent ma...
Fargate Task 2 Container (isolated) No agent ma...
/"Anda kelola: EC2 instances, Capacity planning O..."/
/"Anda kelola: Task definitions, Container code A..."/

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

VPC 10.0.0.0/16 Public Subnets Private Subnets ...

Public Subnet A 10.0.1.0/24

NAT Gateway ENI: 10.0.1.100

Public Subnet B 10.0.2.0/24

ALB ENI: 10.0.2.50

Private Subnet A 10.0.10.0/24

Task 1 ENI: 10.0.10.10

Task 2 ENI: 10.0.10.20

Private Subnet B 10.0.20.0/24

Task 3 ENI: 10.0.20.10

Task 4 ENI: 10.0.20.20



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

  • 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: true pada 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
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