Amazon Elastic Container Service (ECS) is AWS’s fully managed container orchestration platform that lets you run,
stop, and manage Docker containers at any scale without building a control plane.
With ECS you describe the application once—via a Task Definition—and the service takes care of placement, scaling,
rolling updates, and lifecycle. You can choose between two launch types:
EC2 (you manage instances) and Fargate (serverless). For most new workloads, Fargate minimizes
operational overhead while maintaining performance and security isolation.
Tip: Link ECS with Amazon ECR (the managed image registry) to streamline secure image pulls,
scanning, and lifecycle policies.
2) Container Orchestration Made Simple
ECS abstracts cluster complexity: you define tasks, group them into services, and optionally put them behind an
Application Load Balancer (ALB). The scheduler handles placement across
Availability Zones, health checks, and failure remediation.
Rolling and blue/green deployments with CodeDeploy.
Target tracking and step scaling using CloudWatch metrics.
ECS runs Docker-compatible images from ECR or any registry. Keep images lean using multi-stage builds and scan them regularly.
Use immutable tags (e.g., Git SHA) to prevent accidental rollbacks when pushing latest.
Best practice: Use --platform to build for ARM64/AMD64 and match your Fargate/EC2 architecture.
4) Launch Types
EC2: Full control of AMIs, agents, daemonsets, and sidecars. Ideal for specialized hardware.
Fargate: Serverless isolation, per-task billing, simplest ops surface for most apps.
Choose Fargate for baseline; switch to EC2 when you need host-level control.
5) Fargate Integration
Fargate isolates tasks at the runtime boundary, auto patches the infra, and scales on demand. No capacity management.
6) Task Definitions
Blueprint for your containers: images, CPU/memory, env vars, secrets, awslogs, health checks, and volumes.
7) ECS Clusters & Services
A cluster groups compute capacity; a service maintains the desired count of tasks and handles rolling updates.
With ALB target groups, health checks dictate replacement decisions—keep them realistic (timeout,
interval, thresholds) to avoid flapping during cold starts.
99.9%+ Zonal resilience with multi-AZ tasks
<1 min Typical failover on task health failure
Zero-downtime Rolling/blue-green deploys
8) Scaling & Load Balancing
Attach an Application Load Balancer for HTTP/HTTPS and Network Load Balancer for TCP/UDP. Scale via
CloudWatch target tracking (e.g., average CPU 60%) or request rate (ALB RequestCountPerTarget).
Scenario
ALB
NLB
Notes
HTTP APIs
✅
—
Use path/host-based routing, stickiness when stateful.
gRPC / HTTP2
✅
—
Enable HTTP/2, adjust idle timeout.
TCP microservices
—
✅
Ultra-low latency; fewer L7 features.
WebSockets
✅
—
Consider higher idle timeout and connection draining.
awsvpc networking mode gives each task an ENI (own security group, IP). Required for Fargate.
Place tasks in private subnets; route egress via NAT or VPC endpoints for ECR/CloudWatch to reduce cost/egress risk.
Restrict ALB/NLB inbound security groups by CIDR or WAF conditions.
Misrouting to public subnets with overly open SGs is a common audit finding—lock down ports and CIDRs.
10) Security & IAM Integration
ECS embraces least privilege with two roles: the task execution role (pull images, write logs, fetch secrets) and the
task role (your app’s AWS API access). Rotate credentials, use short sessions, and prefer VPC Endpoints for Secrets Manager and SSM.
Encrypt env variables via secrets (SSM/Secrets Manager) instead of plain text.
Enable ECR image scanning and block vulnerable images on deploy with CodePipeline/CodeBuild quality gates.
Use AWS WAF on ALB for Layer-7 protection and bot control.
11) Observability: Logs, Metrics, Traces
Ship STDOUT/STDERR via the awslogs driver to CloudWatch Logs. Emit application metrics to CloudWatch (or Prometheus w/Sidecar) and
use AWS X-Ray for distributed tracing between microservices.
Set structured JSON logging to simplify log insights.
Create AnomalyDetection alarms for sudden spikes in 5XX or latency.
12) CI/CD & DevOps
Use CodePipeline → CodeBuild → ECS blue/green (via CodeDeploy) for zero-downtime updates. For GitHub Actions or GitLab CI, use the
aws-actions/amazon-ecr-login and ECS deploy actions to push images and update services automatically.
Build, test, scan image → push to ECR (immutable tag).
Register new task definition revision.
CodeDeploy switches target group from Green to Blue post health validation.
13) Cost Optimization
Prefer Fargate for bursty loads; tune CPU/Memory to right-size tasks.
For steady 24×7, consider EC2 with Savings Plans or Spot for worker nodes.
Leverage Graviton (ARM64) images; many see 20–30% savings.
Use VPC endpoints for ECR/CloudWatch to reduce NAT egress charges.
Add cost allocation tags (service, env, owner) and build dashboards by team and environment.
14) ECS Anywhere & Hybrid
With ECS Anywhere, register on-prem or edge instances to the ECS control plane. Keep a unified deployment and operations
model while complying with data residency or latency constraints.
15) Real-World Use Cases
Public APIs and web frontends behind ALB with path-based routing.
# 5) Resolve Cloud Map (if used) and ALB DNS
Resolve-DnsName "api.internal.local" -Type A -Server 8.8.8.8
Resolve-DnsName "my-alb-123.ap-south-1.elb.amazonaws.com" -Type A
-- Slow requests > 1s by URL (ALB)
fields @timestamp, @message
| filter elb_status_code >= 500 or target_status_code >= 500
| stats count() as errors by elb, elb_status_code, target_status_code
-- Application JSON logs: top errors
fields @timestamp, level, msg, path
| filter level in ['ERROR','WARN']
| stats count() by msg, path
| sort by count() desc
If tasks flap between PENDING and RUNNING, check: CPU/memory limits, image pull auth (ECR policy), and security group routes to dependencies (DB/Redis).
18) Networking & Security Troubleshooting Matrix
Symptom
Probable Cause
How to Fix
ALB 502/504
Wrong health check path/timeout or container not listening
Align container containerPort and app port; increase health timeout for cold starts.
Task stuck in PENDING
Subnets/SGs misconfigured; no free IPs (awsvpc); insufficient CPU/mem
Use more private IPs (bigger CIDR) or reduce task ENIs; right-size task.
Image pull fails
ECR access denied; no VPC endpoint; rate limited via NAT
Add ECR VPC endpoints; grant execution role permissions; pre-warm cache.
Secrets not found
Task role lacks secretsmanager:GetSecretValue
Attach least-privilege policy to the task role, not just execution role.
Intermittent timeouts
NLB idle timeout, SG egress blocked, DB connections exhausted
Increase timeouts; expand DB pool; confirm SG egress to DB port.
19) Blue/Green Deployments with ALB
Use dual target groups (Blue & Green) and let CodeDeploy shift traffic after health checks and optional automated tests.
Keep backward compatibility during split; version APIs explicitly.
22) Security Hardening (Actionable)
Block :latest tags in production deploys.
Mandatory TLS 1.2+ on ALB listeners; HSTS headers at app layer.
Limit egress with SGs and NACLs; allowlist dependencies by port and CIDR.
Enable secret rotation for database/API keys.
23) Performance Tuning
Right-size cpu and memory to minimize throttling and OOM kills.
Use HEALTHCHECK in Dockerfile plus ECS health checks.
Batch expensive I/O; cache with ElastiCache; reuse connections (HTTP keep-alive).
24) Frequently Asked Questions
Q:When should I prefer ECS over EKS? A: If you want minimal control-plane operations and a native AWS experience with simpler constructs, ECS is faster to value. Choose EKS for Kubernetes-specific ecosystem or portability needs.
Q:Can I mix Fargate and EC2? A: Yes, via separate services or capacity providers; this is common when some tasks need host features and others want serverless simplicity.
Q:Do I need a service mesh? A: Often not. Start with ALB and X-Ray; add App Mesh only if you need retries, timeouts, traffic splitting at L7 among many services.
Blue/Green: CodeDeploy switches the ALB target group after health validation.
Drain Tasks Safely for Maintenance (EC2 launch type)
# Put container instance into DRAINING state so tasks migrate off
$instance = (Get-ECSContainerInstance -Cluster $Cluster)[0].ContainerInstanceArn
Update-ECSContainerInstanceState -Cluster $Cluster -ContainerInstance $instance -Status DRAINING
Find Largest Images & Reclaim Space (EC2 hosts)
# Via SSM: list image sizes to find bloat; requires SSM Agent on hosts
Send-SSMCommand -InstanceId "i-0123456789abcdef0" -DocumentName "AWS-RunShellScript" -Parameter @{ commands = @(
"docker images --format '{{.Repository}}:{{.Tag}} {{.Size}}' | sort -hr -k2 | head -n 20"
)}
# Task role policy example: SSM + Secrets Manager (scope to specific ARNs)
{
"Version": "2012-10-17",
"Statement": [
{"Effect":"Allow","Action":["ssm:GetParameter","ssm:GetParameters"],"Resource":"arn:aws:ssm:ap-south-1:123456789012:parameter/prod/*"},
{"Effect":"Allow","Action":["secretsmanager:GetSecretValue"],"Resource":"arn:aws:secretsmanager:ap-south-1:123456789012:secret:prod/*"}
]
}
31) Blueprints for Different Workloads
Public API: Fargate, ALB, WAF, auto scaling on request rate.
Async worker: SQS trigger via EventBridge schedule; no ALB; DLQ alarms.
Batch ETL: Fargate Spot, EventBridge cron, higher CPU for short runtime.
Place ALB in public subnets; ECS tasks and databases in private subnets with VPC endpoints for control-plane traffic.
32) Key Terms (Quick Glossary)
Task DefinitionServiceClusterCapacity ProviderTarget GroupawsvpcExecution RoleTask Role
33) Conclusion
Amazon ECS unblocks teams to ship reliable, scalable services without the overhead of running a control plane.
Start simple with Fargate, enforce least privilege through IAM roles, observe with CloudWatch/X-Ray, then iterate with
blue/green deploys and cost tuning. With the playbooks and scripts above, you can diagnose 80–90% of incidents within minutes
and restore service confidently.