Cloud / Amazon ECS Interview questions
Last updated
1. What is Amazon ECS?
Amazon Elastic Container Service (ECS) is a fully managed container orchestration service that runs, stops, and manages Docker containers on a cluster.
Instead of you writing scheduling logic, ECS decides which containers land on which compute, restarts failed containers, and keeps the desired number of copies running. You describe your application in a task definition, and ECS handles placement, health tracking, and scaling.
ECS supports two ways to run containers: on EC2 instances you manage, or on AWS Fargate, a serverless compute engine where AWS manages the underlying servers entirely.
Take quiz
Managed relational database service
Container orchestration and scheduling service
Serverless function runtime only
Object storage service
Lambda and S3
EC2 instances and AWS Fargate
RDS and DynamoDB
Snowball and Outposts only
2. What are the launch types supported by Amazon ECS?
ECS supports two launch types that determine where your containers actually run.
- EC2 launch type - tasks run on EC2 instances that you provision, patch, and register into a cluster. You control instance type, AMI, and capacity.
- Fargate launch type - tasks run on serverless compute managed by AWS. You specify CPU and memory for the task, and AWS provisions the underlying infrastructure.
A third option, ECS Anywhere, extends ECS to run tasks on your own on-premises servers or virtual machines using an external launch type.
Take quiz
EC2 launch type
Fargate launch type
External launch type
Spot launch type
ECS Anywhere
ECS Exec
Service Connect
Capacity providers
3. What is a task definition in Amazon ECS?
A task definition is a JSON blueprint that describes one or more containers that make up your application, similar to a docker-compose file for a single deployable unit.
It specifies the container image, CPU and memory limits, port mappings, environment variables, IAM roles, logging configuration, and networking mode. Each time you register changes, ECS creates a new revision rather than overwriting the existing one, so you can roll back.
{ "family": "web-app", "networkMode": "awsvpc", "containerDefinitions": [ { "name": "web", "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/web-app:1.4", "portMappings": [{ "containerPort": 80 }], "memory": 512, "cpu": 256 } ] }
Take quiz
Running instance of a container
JSON blueprint describing containers for a task
Load balancer configuration file
VPC routing table
The old definition is deleted permanently
ECS creates a new revision
The cluster is automatically restarted
The change is rejected
4. What is an ECS cluster?
An ECS cluster is a logical grouping of tasks or services, and, in the EC2 launch type, the underlying container instances that provide compute for them.
A cluster itself doesn't run anything by default - it's a namespace and resource pool. When you launch a Fargate task or EC2-backed task, you tell ECS which cluster to place it in, and ECS tracks capacity, running tasks, and services scoped to that cluster.
You can have multiple clusters per account to separate environments, such as one for staging and one for production.
Take quiz
Single running container
Logical grouping of tasks, services, and capacity
Type of load balancer
Docker image repository
To bypass IAM permissions
To separate environments like staging and production
Because a single cluster can only hold one task
To avoid using task definitions
5. What is an ECS service?
An ECS service keeps a specified number of task instances running continuously, replacing any that stop or fail health checks.
You configure a service with a task definition, a desired count, and optionally a load balancer target group. ECS then continuously reconciles the actual running count against the desired count, launching replacement tasks whenever one is stopped or fails a health check.
Services also manage rolling deployments: when you update the task definition, ECS gradually replaces old tasks with new ones according to your deployment configuration.
Take quiz
Store container images
Maintain a desired number of running tasks
Encrypt data at rest
Route DNS queries
It ignores the failure
It launches a replacement task
It deletes the cluster
It pauses all deployments permanently
6. What are ECS container instances?
A container instance is an EC2 instance that is registered into an ECS cluster and running the ECS container agent.
It's only relevant to the EC2 launch type - Fargate has no visible container instances because AWS manages that layer for you. Each container instance reports its available CPU, memory, and port resources to the ECS control plane, which uses that information to decide where new tasks can be placed.
You manage the instance's OS patching, AMI, and scaling group; ECS manages what runs on top of it.
Take quiz
An EC2 instance registered to an ECS cluster running the ECS agent
A Fargate task
A Docker image stored in ECR
A CloudWatch log group
Fargate only
EC2 launch type
External launch type only
None, they are deprecated
7. What is the ECS container agent?
The ECS container agent is a lightweight process that runs on every EC2 container instance and communicates with the ECS control plane over HTTPS.
It polls ECS for task assignments, starts and stops containers via the local Docker daemon, reports resource utilization and task status back to ECS, and forwards container health information. Without a healthy agent, ECS cannot place new tasks on that instance or receive status updates from it.
On Fargate, an equivalent agent exists but is fully managed - you never install or patch it yourself.
Take quiz
The AWS control plane only
Each EC2 container instance
The client's laptop
Amazon S3
ECS cannot place new tasks or get status from that instance
The cluster is deleted automatically
All tasks in the account stop
Nothing, the agent is optional
8. How do you use environment variables in an ECS task definition?
You define environment variables directly on each container inside the task definition using the environment field for plain values, or secrets for sensitive values pulled from AWS Secrets Manager or Systems Manager Parameter Store.
"environment": [ { "name": "LOG_LEVEL", "value": "info" } ], "secrets": [ { "name": "DB_PASSWORD", "valueFrom": "arn:aws:ssm:...:parameter/db-password" } ]
Plain values are visible in the task definition JSON and console, so they suit non-sensitive configuration like feature flags or log levels. Anything sensitive, such as passwords or API keys, should go through secrets so it's resolved at container start rather than stored in plaintext.
Take quiz
environment
secrets
portMappings
volumes
Only inside the Docker image
AWS Secrets Manager or SSM Parameter Store
The container's local filesystem
A public S3 bucket
9. Define Fargate launch type in ECS?
Fargate is a serverless compute engine for containers where you specify only the CPU and memory your task needs, and AWS provisions, scales, and patches the underlying infrastructure automatically.
There are no EC2 instances to manage, no capacity to pre-provision, and no host-level patching. Each Fargate task runs in its own isolated compute environment, which also improves security isolation between tasks compared to sharing an EC2 host.
Fargate is billed per task based on the vCPU and memory reserved for the duration it runs, plus an optional Fargate Spot discounted mode for interruption-tolerant workloads.
Take quiz
EC2 instance patching
Only the task's CPU and memory specification
The cluster autoscaling group
The host operating system
Each task runs in its own isolated compute environment
It disables networking entirely
It requires shared hosts by design
It removes IAM roles
10. What are the task networking modes available in ECS?
ECS supports four networking modes, configured per task definition:
| Mode | Behavior |
| awsvpc | Each task gets its own elastic network interface and private IP; required for Fargate. |
| bridge | Uses Docker's built-in virtual network on the host (EC2 launch type only). |
| host | Container ports map directly to the host's network interface (EC2 only). |
| none | Networking is disabled for the task. |
Fargate tasks must use awsvpc; EC2 tasks can use any of the four depending on isolation and port-management needs. The mode is set once, at the task-definition level, via the networkMode field, so switching between them later means registering a new revision rather than changing a running task in place.
Take quiz
host
bridge
awsvpc
none
awsvpc
host
none
bridge
11. What is the awsvpc network mode?
In awsvpc mode, each ECS task receives its own elastic network interface (ENI) with a private IP address from your VPC subnet, just like an EC2 instance would.
This means every task gets its own security group rules, its own ENI-level flow logs, and no port conflicts with other tasks on the same host, since each task effectively has its own network stack. It also lets you attach an Application Load Balancer directly to the task's IP rather than to a dynamic host port.
awsvpc is required for Fargate tasks and is the recommended mode for EC2 tasks needing per-task security isolation.
Take quiz
A shared IP with all other tasks on the host
Its own elastic network interface and private IP
No networking at all
Only a host port mapping
Per-task security groups and no port conflicts between tasks
Mandatory use of the host's root network namespace
Elimination of VPC subnets
Disabling of load balancer integration
12. Describe the ECS task lifecycle states?
An ECS task moves through a defined sequence of states from creation to termination:
flowchart LR A[PROVISIONING] --> B[PENDING] B --> C[ACTIVATING] C --> D[RUNNING] D --> E[DEACTIVATING] E --> F[STOPPING] F --> G[DEPROVISIONING] G --> H[STOPPED]
- PROVISIONING - resources like ENIs are being set up (awsvpc mode).
- PENDING - ECS is placing the task and pulling container images.
- ACTIVATING - additional setup, such as Service Connect proxies, is running.
- RUNNING - all containers have started successfully.
- DEACTIVATING / STOPPING / DEPROVISIONING - graceful shutdown steps.
- STOPPED - the task has fully terminated, with a
stoppedReasonrecorded.
Take quiz
RUNNING
PENDING
STOPPED
DEACTIVATING
A new task definition revision
A stoppedReason value
A new ENI
A CloudFormation stack
13. What is a capacity provider in ECS?
A capacity provider tells ECS where and how to obtain the compute capacity for your tasks, decoupling the "what to run" (task definitions) from the "where to run it" (capacity source).
ECS offers built-in capacity providers FARGATE and FARGATE_SPOT, and for EC2 you create custom capacity providers backed by an Auto Scaling group. A cluster can use a capacity provider strategy that mixes multiple providers with a weight (relative distribution) and base (minimum guaranteed count).
This lets a service, for example, run a guaranteed baseline on regular Fargate while bursting onto cheaper Fargate Spot capacity.
Take quiz
Container image versions
Where and how compute capacity is obtained for tasks
The VPC CIDR range
IAM policy documents
The relative percentage split between providers
The minimum guaranteed task count on that provider
The maximum CPU per task
The container image tag
14. What are ECS placement strategies?
Placement strategies tell ECS how to choose among the available candidate instances when launching a task on the EC2 launch type (Fargate manages placement for you).
- binpack - packs tasks onto the fewest instances by CPU or memory, minimizing idle capacity.
- spread - distributes tasks evenly across a specified field, such as Availability Zone or instance ID, for high availability.
- random - places tasks on a random valid instance.
You can combine strategies, such as spreading across Availability Zones first and then binpacking within each zone, by listing multiple strategy rules in order of priority.
Take quiz
spread
binpack
random
distinctInstance
binpack
random
spread
none
15. What is ECS Service Connect?
ECS Service Connect gives ECS services simple DNS-based service discovery and automatic traffic metrics between services, without requiring a separate service mesh.
When enabled, ECS injects a lightweight proxy into each task that intercepts traffic, resolves logical service names like orders.internal, and reports request counts, latency, and error rates directly in the ECS console and CloudWatch, no manual instrumentation required.
It's aimed at teams who want reliable service-to-service calls and built-in observability without the operational overhead of running a full mesh like App Mesh.
Take quiz
Block storage for tasks
DNS-based service discovery with built-in traffic metrics
IAM role assumption
Container image scanning
By injecting a lightweight proxy into each task
By requiring developers to write custom logging code
By scanning the container image at build time
By polling CloudTrail logs
16. What is the ECS task execution role?
The task execution role is an IAM role that the ECS agent itself assumes on your behalf to perform infrastructure-level actions needed to launch a task.
It typically grants permission to pull container images from ECR, write logs to CloudWatch Logs, and retrieve values referenced in the secrets field from Secrets Manager or SSM Parameter Store. It is not used by your application code at runtime.
Every task that pulls a private image or uses injected secrets needs an execution role attached in its task definition's executionRoleArn field.
Take quiz
Your application code inside the container
The ECS agent, to launch the task
An IAM user logging into the console
The Application Load Balancer
Pulling images from ECR and writing logs to CloudWatch
Modifying Route 53 hosted zones
Deleting VPCs
Managing billing alerts
17. What is the ECS task role?
The task role is an IAM role assumed by the application code running inside the container, granting it permissions to call other AWS services such as S3, DynamoDB, or SQS.
Credentials are delivered securely via a per-task metadata endpoint, so the application never needs hardcoded AWS access keys. This is distinct from the execution role, which the ECS agent uses only for launch-time operations like pulling images.
Following least privilege, each task definition should have a task role scoped only to the specific AWS APIs that application actually needs.
Take quiz
The ECS control plane only
Application code running inside the container
The Auto Scaling group
The Docker daemon on the host
Via a per-task metadata endpoint
By hardcoding access keys in the image
Through an SSH session
Via a shared instance profile only
18. How do you deploy a container to ECS?
Deploying to ECS generally follows a repeatable sequence:
- Build the Docker image and push it to a registry, typically Amazon ECR.
- Write or update a task definition that references the new image tag.
- Register the task definition, which creates a new revision.
- Update the ECS service to use that revision, or run a standalone task.
- ECS performs a rolling deployment, starting new tasks and draining old ones based on your deployment configuration.
This can be done via the AWS Console, CLI (aws ecs update-service), CloudFormation, CDK, or CI/CD pipelines such as CodePipeline or GitHub Actions.
Take quiz
Deleting the cluster
Building the image and pushing it to a registry like ECR
Disabling the load balancer
Removing the task role
aws ecs delete-cluster
aws ecs update-service
aws ecr create-repository
aws ec2 run-instances
19. What is ECR and how does it relate to ECS?
Amazon Elastic Container Registry (ECR) is a managed Docker image registry for storing, versioning, and scanning container images.
ECS pulls container images referenced in a task definition's image field, and while ECS can pull from any accessible registry (Docker Hub, GHCR, etc.), ECR is the natural default because it integrates directly with IAM for access control and with the task execution role for authentication - no separate registry credentials need to be managed.
ECR also supports image scanning for vulnerabilities and lifecycle policies to automatically clean up old image tags.
Take quiz
A container orchestration engine
A managed Docker image registry
A load balancing service
A DNS resolution service
It requires no IAM permissions at all
Authentication happens via the task execution role, avoiding separate credentials
It replaces the need for task definitions
It automatically rewrites application code
20. What are ECS placement constraints?
Placement constraints restrict which instances are eligible to run a task, based on rules rather than optimization, unlike placement strategies which optimize distribution.
- distinctInstance - ensures each task in a group runs on a different container instance.
- memberOf - restricts placement to instances matching a cluster query language expression, such as a specific instance type or custom attribute.
"placementConstraints": [ { "type": "memberOf", "expression": "attribute:ecs.instance-type == c5.large" } ]
Constraints are useful for licensing requirements tied to specific hardware, or ensuring redundant copies of a task never share a single point of failure.
Take quiz
memberOf
distinctInstance
binpack
spread
Optimize for cost only
Enforce hard eligibility rules rather than optimizing distribution
Only apply to Fargate tasks
Are set at the VPC level
21. List the deployment types supported by ECS services?
ECS services support three deployment controller types:
- Rolling update (ECS) - the default; ECS incrementally replaces old tasks with new ones based on minimum/maximum healthy percent settings.
- Blue/green (CODE_DEPLOY) - AWS CodeDeploy provisions a parallel "green" task set, shifts traffic via load balancer listener rules, and can automatically roll back on alarms.
- External - you supply your own custom deployment logic and task set management, typically for advanced third-party orchestration integrations.
Rolling updates are simplest to operate; blue/green offers safer, instant traffic cutover and rollback at the cost of extra CodeDeploy setup.
Take quiz
Rolling update
Blue/green
External
Canary-only
External
Blue/green
Rolling update
Manual
22. What is ECS Anywhere?
ECS Anywhere extends the ECS control plane to manage containers running on infrastructure outside AWS - your own data center servers or virtual machines.
You install the ECS agent and SSM agent on your external server, register it with ECS using an activation key, and it then appears as a container instance using the EXTERNAL launch type. From there, task definitions, services, and most ECS APIs work the same way they would for an EC2-backed cluster.
It's aimed at hybrid environments where teams want a single consistent orchestration API across cloud and on-premises workloads.
Take quiz
Run containers exclusively inside AWS Lambda
Manage containers on your own on-premises infrastructure
Replace Amazon ECR
Disable IAM roles
FARGATE
EC2
EXTERNAL
SPOT
23. How do you enable logging for ECS tasks?
You configure a log driver in the container definition's logConfiguration block. The most common driver is awslogs, which streams container stdout/stderr directly to CloudWatch Logs.
"logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "/ecs/web-app", "awslogs-region": "us-east-1", "awslogs-stream-prefix": "web" } }
The task execution role must include permission to create log streams and put log events. Other supported drivers include splunk, fluentd, and awsfirelens for routing logs to third-party aggregators. Once configured, logs appear automatically in the specified CloudWatch log group, organized into a separate stream per task so you can trace output back to a specific task ID.
Take quiz
fluentd
awslogs
syslog
none
Task role
Task execution role
Service-linked role for EC2
None, logging needs no permissions
24. What is Fargate Spot?
Fargate Spot runs Fargate tasks on spare AWS compute capacity at a significant discount compared to standard Fargate pricing, in exchange for the possibility of interruption with a two-minute warning.
It's suited to fault-tolerant, stateless, or batch-style workloads - things like CI runners, queue consumers, or non-critical background processing - where an occasional task restart is acceptable. You typically mix it with regular Fargate in a capacity provider strategy, keeping a guaranteed baseline on standard Fargate and bursting extra capacity onto Spot.
It should be avoided for workloads that cannot tolerate abrupt termination, such as long-running stateful sessions.
Take quiz
Unlimited guaranteed uptime
The possibility of task interruption
Removing IAM support
Losing access to CloudWatch logs
Long-running stateful sessions that cannot restart
Fault-tolerant, interruption-tolerant workloads
Databases requiring constant uptime
Licensing-restricted legacy applications
25. What is the difference between ECS and EKS?
Both run containers on AWS, but they use different orchestration models and APIs.
| Amazon ECS | Amazon EKS |
| AWS-native, proprietary orchestration API and control plane. | Managed Kubernetes control plane, using standard Kubernetes APIs. |
| Simpler to learn; tightly integrated with other AWS services. | Steeper learning curve; portable across clouds and on-prem via kubectl/YAML. |
| No control plane fee for the ECS layer itself. | Charges a per-cluster control plane fee. |
Teams already invested in Kubernetes tooling, or needing multi-cloud portability, tend to pick EKS. Teams wanting the fastest path to running containers on AWS with minimal operational overhead tend to pick ECS. Both can run on either EC2 or Fargate compute, so the choice usually comes down to orchestration API preference rather than compute options.
Take quiz
ECS
EKS
Both equally
Neither
Multi-cloud Kubernetes portability
A simpler, AWS-native orchestration model with less operational overhead
Mandatory use of kubectl
Lower container density
26. What is the difference between Fargate and EC2 launch types?
The core distinction is who manages the underlying servers.
| Fargate | EC2 launch type |
| AWS provisions and patches compute per task. | You provision, patch, and scale EC2 instances yourself. |
| Billed per task, by vCPU/memory reserved. | Billed per EC2 instance, regardless of task packing efficiency. |
| Task-level network and compute isolation. | Tasks can share a host, requiring more careful resource planning. |
| No access to host-level customization (GPU support limited). | Full control - custom AMIs, GPU instances, host networking mode. |
Choose Fargate for operational simplicity; choose EC2 launch type when you need tighter cost control at scale, specific instance types, or host-level customization.
Take quiz
AWS
You
Neither, patching is unnecessary
Amazon ECR
EC2 launch type
Fargate
Both equally
Neither
27. What is the difference between a task role and an execution role in ECS?
Although both are IAM roles attached to a task definition, they serve different actors at different times.
| Task Role | Task Execution Role |
| Used by the application code inside the container at runtime. | Used by the ECS agent to launch the task, before the app even starts. |
| Grants access to app-level AWS APIs, e.g. S3, DynamoDB, SQS. | Grants access to pull ECR images, write CloudWatch logs, fetch secrets. |
Set via taskRoleArn. |
Set via executionRoleArn. |
Mixing them up is a common misconfiguration: granting S3 access on the execution role instead of the task role, for example, does nothing for your application code, since the app never assumes the execution role.
Take quiz
Task execution role
Task role
Neither, it's automatic
Cluster service role
Granting app-level permissions on the execution role instead of the task role
Using awsvpc mode with Fargate
Registering a new task definition revision
Enabling CloudWatch logging
28. What is the difference between bridge, host, and awsvpc network modes?
The three EC2-compatible network modes trade off isolation against simplicity differently.
| bridge | host | awsvpc |
| Docker's virtual bridge network on the host. | Container shares the host's network namespace directly. | Each task gets its own ENI and private IP. |
| Dynamic host ports avoid conflicts. | Container port must equal host port; no dynamic mapping. | No host port conflicts; per-task security groups. |
| EC2 launch type only. | EC2 launch type only. | Required for Fargate; optional for EC2. |
host mode gives the best raw network performance but the least isolation. awsvpc gives the strongest isolation and is the only mode Fargate supports. In practice, most new EC2-based services default to awsvpc unless there's a specific reason - like needing dynamic port mapping across many tasks per host - to choose bridge instead.
Take quiz
bridge
host
awsvpc
none
bridge
host
awsvpc
none
29. Why should you use Fargate over EC2 launch type?
Fargate removes an entire operational layer: there's no AMI to patch, no capacity to pre-provision, and no Auto Scaling group to tune for headroom.
This matters most when a team's priority is shipping features rather than managing infrastructure, when workloads are spiky and hard to right-size on EC2 without waste, or when strict per-task network and compute isolation is a security requirement. Billing aligns directly with the resources a task actually reserves, rather than paying for whole EC2 instances that may be under-packed.
The trade-off is less control - you can't choose custom AMIs, GPU-backed instances (beyond limited Fargate GPU support), or host networking mode - so very cost-sensitive, high-density workloads may still favor EC2 launch type for tighter bin-packing.
Take quiz
Eliminating the need to patch or provision servers
Guaranteed lower total cost at any scale
Mandatory GPU access
Unlimited host networking control
Wanting tighter bin-packing and custom AMI/instance control at scale
Avoiding IAM roles entirely
Fargate cannot run containers
EC2 launch type has no patching responsibility
30. Why do we use task placement strategies in ECS?
Placement strategies exist because, on the EC2 launch type, multiple valid instances could host a new task, and the "best" choice depends on your goals - cost efficiency versus fault tolerance.
Without a strategy, ECS would place tasks somewhat arbitrarily among eligible instances, potentially clustering all replicas of a service on one Availability Zone (a resilience risk) or spreading them thinly across many under-utilized instances (a cost inefficiency). By explicitly choosing binpack, spread, or a combination, you make that trade-off intentional.
A common real pattern is spreading across Availability Zones for resilience first, then binpacking within each zone to reduce the number of instances paid for.
Take quiz
Tasks may cluster in one Availability Zone, hurting resilience
ECS refuses to place any tasks
All containers are forced onto Fargate
IAM roles are ignored
Random placement only, always
Spread across AZs first, then binpack within each zone
Binpack across zones, ignoring AZ resilience
Disabling placement entirely on EC2
31. How does ECS service auto scaling work?
ECS service auto scaling uses Application Auto Scaling to adjust a service's desired task count based on real-time metrics.
You register the service as a scalable target with a minimum and maximum task count, then attach one or more scaling policies:
- Target tracking - keeps a metric like average CPU utilization or ALB request count per task near a target value, automatically calculating how many tasks to add or remove.
- Step scaling - adds or removes a specific number of tasks based on how far a CloudWatch alarm threshold is breached.
- Scheduled scaling - changes desired count at fixed times, useful for predictable daily traffic patterns.
This adjusts task count only. If you're on the EC2 launch type, you separately need cluster capacity providers or Auto Scaling group scaling to ensure enough underlying instance capacity exists for those extra tasks.
Take quiz
Application Auto Scaling
AWS Backup
Amazon Inspector
AWS Config
Nothing else is ever needed
Cluster capacity provider or ASG scaling for underlying instance capacity
Disabling Fargate
A new VPC for every scale event
32. How does ECS deployment circuit breaker work?
The deployment circuit breaker detects failed deployments automatically and rolls back to the last known-good task definition, instead of leaving a service stuck retrying a broken revision indefinitely.
flowchart TD
A["New deployment starts"] --> B["New tasks launched"]
B --> C{Tasks reach RUNNING and pass health checks?}
C -- Yes --> D["Deployment completes"]
C -- No, repeated failures --> E["Circuit breaker trips"]
E --> F["Automatic rollback to previous task definition"]
You enable it per service with a rollback option. ECS counts consecutive task failures during rollout, and once a failure threshold is crossed, it stops launching more failing tasks and, if rollback is enabled, redeploys the prior stable revision automatically - reducing manual intervention during a bad release.
Take quiz
A single successful task launch
Repeated consecutive task failures during rollout
Manually stopping the cluster
Changing the VPC CIDR
Delete the entire cluster
Redeploy the previous stable task definition automatically
Ignore the failure and keep retrying forever
Switch the launch type to EC2
33. How is service discovery implemented in ECS?
ECS offers two main paths for services to find and call each other by name instead of hardcoded IPs.
sequenceDiagram participant OrdersTask as Orders Task participant CloudMap as AWS Cloud Map / DNS participant PaymentsTask as Payments Task OrdersTask->>CloudMap: Resolve "payments.internal" CloudMap-->>OrdersTask: Return current healthy IP(s) OrdersTask->>PaymentsTask: Send request directly
- AWS Cloud Map integration - ECS automatically registers and deregisters task IPs as a private DNS namespace, updated as tasks scale or replace.
- ECS Service Connect - builds on Cloud Map but adds a managed proxy per task, giving DNS resolution plus built-in metrics and simpler configuration.
Both remove the need to manually track changing task IPs behind a load balancer for internal service-to-service traffic.
Take quiz
AWS Cloud Map
AWS Config
Amazon Macie
AWS Trusted Advisor
Nothing, they are identical
A managed per-task proxy with built-in traffic metrics
Mandatory public internet exposure
Removal of DNS resolution
34. When should you choose the binpack placement strategy?
Choose binpack when your priority is cost efficiency on the EC2 launch type - packing as many tasks as possible onto the fewest running instances, based on CPU or memory as the packing dimension.
This is a good fit for batch or background-processing clusters where instances can be safely scaled in once utilization drops, since binpack naturally leaves some instances empty and ready for termination by the Auto Scaling group. It's a weaker fit for latency-sensitive, customer-facing services where you'd rather spread load and reduce blast radius per host.
In practice, many teams combine it with a spread strategy across Availability Zones first, then binpack within each zone.
Take quiz
Maximum Availability Zone spread
Cost efficiency by minimizing instances used
Random distribution
GPU availability
Batch processing clusters that scale in easily
Latency-sensitive customer-facing services needing spread for resilience
Cost-sensitive background workloads
Clusters with idle capacity to reclaim
35. When would you choose EC2 launch type over Fargate?
EC2 launch type makes sense when you need capabilities Fargate doesn't fully expose, or when running at a scale where bin-packing savings outweigh the operational overhead.
- You need GPU instance types beyond what Fargate currently offers, or specialized instance families.
- You want host networking mode for maximum network throughput.
- You run many small, bursty tasks and can bin-pack them tightly onto fewer, larger instances for lower effective cost than per-task Fargate pricing.
- You need custom AMIs, kernel-level tuning, or specific EC2 reserved/savings plan commitments already in place.
If none of these apply, Fargate's reduced operational burden usually wins by default. Many teams also start every new service on Fargate and only migrate specific, well-understood workloads to EC2 launch type once a concrete cost or capability driver justifies the added operational work.
Take quiz
Zero infrastructure management
GPU instance types or host networking mode
Per-task billing only
Automatic host patching
Increase per-task isolation above awsvpc levels
Lower effective compute cost versus per-task Fargate pricing
Avoid using task definitions
Disable Auto Scaling groups
36. What happens when an ECS task fails its health check?
The outcome depends on which health check failed, but the general pattern is the same: ECS (or the load balancer) marks the task unhealthy, stops routing traffic to it, and the service scheduler replaces it.
- If a container health check (defined in the task definition) fails repeatedly past its retry threshold, ECS marks the container - and therefore the task - as
UNHEALTHYand stops it. - If an ELB target group health check fails, the load balancer stops sending new requests to that task's IP/port, and ECS eventually stops the task once it's confirmed unhealthy for long enough.
- In both cases, if the task belongs to a service, the scheduler launches a replacement to restore the desired count.
Standalone tasks (not part of a service) are not automatically replaced - they simply stop.
Take quiz
Leave the desired count permanently reduced
Launch a replacement task automatically
Delete the entire service
Switch the cluster's launch type
Is automatically replaced like a service task
Simply stops, with no automatic replacement
Triggers a full cluster rollback
Is moved to a different cluster
37. What is the difference between minimum healthy percent and maximum percent in ECS deployments?
These two settings jointly control how aggressively a rolling deployment replaces tasks.
| minimumHealthyPercent | maximumPercent |
| The lowest percentage of the desired count that must stay running/healthy during deployment. | The highest percentage of the desired count allowed to run at once, including new tasks being added. |
| Controls how much capacity can be taken down at a time. | Controls how much extra capacity can be launched before old tasks are removed. |
| Default 100% for many service types. | Default 200%, allowing a full doubling during rollout. |
For example, with desired count 4, minimum 100%, and maximum 200%, ECS can launch up to 4 new tasks before terminating any old ones, guaranteeing zero capacity loss during rollout.
Take quiz
The maximum extra tasks allowed during rollout
The lowest percentage of desired capacity that must remain running
The container's CPU reservation
The VPC subnet count
2
4
8
0
38. How can you optimize ECS task cost?
Cost optimization on ECS usually comes from a mix of right-sizing, capacity mix, and scheduling choices rather than any single setting.
- Right-size CPU/memory - use CloudWatch Container Insights to find over-provisioned tasks and trim reservations to match actual usage.
- Mix in Fargate Spot or EC2 Spot for interruption-tolerant workloads via a capacity provider strategy with a small guaranteed base and a larger weighted Spot portion.
- Bin-pack on EC2 launch type using the binpack placement strategy to reduce idle instance capacity.
- Scale to zero or low counts off-hours with scheduled Application Auto Scaling for non-production or predictable-traffic services.
- Use Savings Plans covering Fargate or EC2 compute for steady-state baseline usage.
The right combination depends on whether workloads are steady-state (favor commitments and bin-packing) or bursty (favor Spot and autoscaling).
Take quiz
CloudWatch Container Insights
Amazon Route 53
AWS Direct Connect
Amazon Cognito
Running exclusively on-demand at maximum reservation
Mixing in Fargate Spot via a capacity provider strategy
Disabling auto scaling entirely
Avoiding task definitions
39. How do you troubleshoot a task stuck in PENDING state?
A task lingering in PENDING usually means ECS can't finish placing or starting it, and the fix depends on the launch type and root cause.
- Check service events in the console or via
aws ecs describe-services- ECS often logs a human-readable reason, like insufficient CPU/memory or ENI limits reached. - Image pull failures - verify the execution role has ECR permissions and the image URI/tag exists.
- ENI/subnet exhaustion (awsvpc mode) - confirm the subnet has free IP addresses and the security group/route table allow required traffic.
- Insufficient EC2 capacity (EC2 launch type) - check if the cluster has container instances with enough free CPU/memory, or if the Auto Scaling group needs to scale out.
- Task definition errors - invalid resource limits or missing required fields can prevent scheduling entirely.
Cross-referencing stoppedReason on any related failed tasks and CloudWatch Logs for the container agent narrows this down quickly.
Take quiz
ECS service events
The VPC flow logs only
The billing console
Route 53 health checks
Too many available container instances
Insufficient free CPU/memory on container instances
Having a valid task role
Using the awslogs driver
40. Explain the execution flow of an ECS task launch?
Launching a task, whether from a service or a one-off RunTask call, follows a consistent sequence through the ECS control plane:
sequenceDiagram participant User as Caller (Service/RunTask) participant ECS as ECS Control Plane participant Sched as Scheduler participant Infra as Fargate/EC2 Instance participant Agent as Container Agent User->>ECS: Request task launch ECS->>Sched: Evaluate placement (strategy/constraints) Sched-->>ECS: Selected target capacity ECS->>Infra: Provision ENI (awsvpc) / assign instance ECS->>Agent: Assign task Agent->>Agent: Pull image(s), start containers Agent-->>ECS: Report RUNNING + health status
- ECS receives the launch request and validates the task definition.
- The scheduler evaluates placement strategies/constraints (EC2) or allocates Fargate capacity.
- Networking resources are provisioned if using awsvpc mode.
- The container agent pulls images (using the execution role) and starts containers in the order defined by
dependsOn. - The agent reports status back, transitioning the task through PENDING to RUNNING once all containers and health checks pass.
Take quiz
The Application Load Balancer
The ECS scheduler
Amazon Route 53
The IAM policy engine
Task role
Task execution role
Root AWS account credentials
No role is needed
41. Explain the internal working of the ECS container agent?
The container agent acts as the bridge between the ECS control plane and the local Docker (or containerd) runtime on a container instance.
sequenceDiagram participant ECS as ECS Control Plane participant Agent as Container Agent participant Docker as Docker Daemon Agent->>ECS: Long-poll for task assignments (HTTPS) ECS-->>Agent: Send task payload Agent->>Docker: Pull image, create & start containers Docker-->>Agent: Container state changes Agent->>ECS: Report task/container status
Internally, it maintains a persistent HTTPS connection to the ECS backend, listening for state change requests. When it receives a new task, it translates the task definition into Docker API calls - pulling images, creating containers with the specified CPU/memory limits, and wiring up networking per the chosen network mode.
It also exposes a local task metadata and stats endpoint inside each container, which application code or sidecars can query for information like the task ARN or resource utilization. If the agent itself is disconnected, existing tasks keep running, but ECS cannot place new ones or receive updates until connectivity is restored.
Take quiz
A persistent HTTPS long-poll connection
SMTP email
SSH tunnel initiated by ECS
FTP polling
They are immediately terminated
They keep running, but ECS can't place new tasks or get updates
The cluster is deleted
They are moved to Fargate automatically
42. Explain the lifecycle of an ECS service deployment?
An ECS service deployment progresses through a controlled replacement of task sets, tracked as a distinct deployment object on the service.
flowchart TD
A["Update service with new task definition"] --> B["New PRIMARY deployment created"]
B --> C["Launch new tasks up to maximumPercent"]
C --> D{New tasks healthy?}
D -- Yes --> E["Drain and stop old tasks down to minimumHealthyPercent"]
E --> F["Old deployment reaches 0 tasks"]
F --> G["Deployment COMPLETED"]
D -- No, repeated failures --> H["Circuit breaker rollback if enabled"]
- Updating a service's task definition creates a new PRIMARY deployment while the current one becomes ACTIVE.
- New tasks launch gradually, respecting
maximumPercent. - As new tasks pass health checks, old tasks are deregistered from any load balancer target group and stopped, respecting
minimumHealthyPercent. - Once the old deployment reaches zero tasks, it's removed and the new deployment becomes the sole PRIMARY, marked COMPLETED.
If the deployment circuit breaker is enabled and new tasks keep failing, the service rolls back to the previous deployment instead of completing.
Take quiz
A new cluster
A new PRIMARY deployment
A new VPC
A new IAM user
maximumPercent only
minimumHealthyPercent
The task's image tag
The cluster's region
43. What is the difference between ECS Service Connect and AWS App Mesh?
Both help services communicate reliably, but they target different levels of complexity and control.
| Service Connect | App Mesh |
| Built into ECS; minimal setup, DNS + basic metrics. | Full service mesh; separate resource to configure (virtual nodes, routers, routes). |
| Good default observability out of the box. | Fine-grained traffic control: retries, circuit breaking, weighted routing, mTLS. |
| Simpler mental model, less flexible. | More powerful, more operational overhead. |
Choose Service Connect for straightforward service-to-service calls with built-in metrics and minimal configuration. Choose App Mesh when you need advanced traffic shaping, canary releases, or mutual TLS across a large microservices estate. Some organizations start with Service Connect and only adopt App Mesh later once traffic-management requirements outgrow what Service Connect exposes.
Take quiz
Service Connect
App Mesh
Both identically
Neither
Maximum configuration complexity
Simple setup with built-in DNS discovery and metrics
Mandatory use of Kubernetes
To disable service discovery entirely
44. How does blue/green deployment work with ECS and CodeDeploy?
Blue/green deployment on ECS uses AWS CodeDeploy as the deployment controller instead of ECS's native rolling updater, giving instant traffic cutover and automated rollback.
flowchart TD
A["Deploy new task definition"] --> B["CodeDeploy creates GREEN task set"]
B --> C["Health checks pass on GREEN"]
C --> D["Traffic shifted from BLUE to GREEN via listener rule"]
D --> E{CloudWatch alarms healthy?}
E -- Yes --> F["BLUE task set terminated"]
E -- No --> G["Automatic rollback to BLUE"]
- CodeDeploy provisions a second, parallel GREEN task set alongside the existing BLUE one.
- Once GREEN passes its health checks, an ALB listener rule shifts traffic - all at once or gradually (canary/linear).
- CodeDeploy monitors CloudWatch alarms during a bake time; if they trip, it automatically reroutes traffic back to BLUE.
- If healthy, the old BLUE task set is terminated after the bake period.
This avoids the mixed-version window inherent to rolling updates, at the cost of needing double capacity briefly and additional CodeDeploy configuration.
Take quiz
AWS CodeDeploy
Amazon SNS
AWS Config
Amazon GuardDuty
Ignore the alarms and finish the deployment
Automatically roll traffic back to the BLUE task set
Delete the cluster
Switch the launch type to EC2
45. Why doesn't a stopped ECS task automatically restart?
Whether a stopped task restarts depends entirely on how it was launched, not on ECS "forgetting" about it.
A task launched directly via RunTask is a standalone unit with no supervisor watching it - once it stops, for any reason, ECS considers its job done and takes no further action. Restart behavior only exists at the service level: a service continuously compares the actual running count to its desired count and launches replacements for any service-managed task that stops, whether due to a crash, a deployment, or manual termination.
So a standalone task stopping is expected behavior, not a failure of ECS - if you need self-healing, run the workload as a service (or use EventBridge Scheduler / Step Functions to relaunch one-off tasks on a schedule or condition).
Take quiz
The task definition itself
An ECS service comparing running count to desired count
The container agent alone
Amazon ECR
Automatically relaunched by ECS
Not automatically relaunched, since no service supervises it
Converted into a service
Moved to a different cluster
46. How do you implement sidecar containers in ECS task definitions?
A sidecar is an additional container in the same task definition that supports the main application container - for logging, proxying, or metrics collection - sharing the task's network namespace and, optionally, storage volumes.
"containerDefinitions": [ { "name": "app", "image": "app:1.0", "dependsOn": [ { "containerName": "log-router", "condition": "START" } ]}, { "name": "log-router", "image": "amazon/aws-for-fluent-bit:latest" } ]
Because containers in one task definition share the same ENI (in awsvpc mode) and can share mounted volumes, a sidecar can intercept traffic on localhost, tail log files written to a shared volume, or proxy outbound calls, without any extra networking setup.
Use dependsOn with a condition like START or HEALTHY to control startup order, ensuring the sidecar is ready before the main application container starts if it depends on it.
Take quiz
Nothing at all with the main container
The task's network namespace and optionally storage volumes
A separate task definition entirely
A different IAM account
portMappings
dependsOn
networkMode
placementConstraints
47. What is the difference between dynamic and static port mapping in ECS?
Port mapping determines how a container's exposed port is reachable from outside, and it behaves differently depending on network mode.
| Static mapping | Dynamic mapping |
| A fixed host port is set explicitly (e.g., host 8080 to container 80). | Host port is left as 0; Docker assigns an available ephemeral port at runtime. |
| Only one task per container port can run per host (bridge/host mode). | Multiple tasks per host can share the same container port, since host ports differ. |
| Common with host network mode. | Common with bridge mode behind an ALB, which tracks the assigned port automatically. |
With awsvpc mode, this distinction mostly disappears, since each task has its own IP and can use the same container port without any host-level conflict at all.
Take quiz
Forces every task to use the same fixed host port
Lets multiple tasks share a host without container port conflicts
Removes the need for a load balancer
Only works with the awsvpc mode
Each task gets its own IP address, avoiding host port conflicts
awsvpc disables all networking
Only one task can ever run under awsvpc
Load balancers are not supported
48. How does cluster auto scaling work with capacity providers?
For EC2-backed clusters, capacity providers link an Auto Scaling group (ASG) to ECS through a managed scaling configuration, so the ASG grows or shrinks based on actual task demand rather than raw instance-level metrics alone.
flowchart TD
A["Service requests more tasks"] --> B{Enough free capacity on instances?}
B -- No --> C["Capacity Provider triggers ASG scale-out via managed scaling"]
C --> D["New EC2 instances register as container instances"]
D --> E["Pending tasks placed on new capacity"]
B -- Yes --> E
E --> F["Idle instances later scaled-in by managed termination protection rules"]
ECS computes a target capacity percentage - how full instances should be - and reports a CloudWatch metric that the ASG's scaling policy consumes to add or remove instances. Managed termination protection ensures instances aren't terminated while they still host running tasks, avoiding disruptive mid-task instance removal.
Take quiz
An S3 bucket
An Auto Scaling group via managed scaling
A Route 53 hosted zone
A Lambda function
Instances from ever scaling out
Instances hosting running tasks from being terminated mid-task
Tasks from using the awsvpc mode
Services from ever updating
49. Which is better and why: awsvpc mode vs bridge mode for security?
awsvpc mode is generally the stronger choice for security-sensitive workloads, though the right answer depends on context.
Because each task gets its own elastic network interface, you can apply per-task security groups - a task handling payment data can have tighter inbound/outbound rules than a task serving static assets, even on the same cluster. Bridge mode, by contrast, shares the host's network stack across all tasks on that instance, so security groups apply at the instance level, and a compromised container has more opportunity for network-level lateral movement toward its neighbors.
The trade-off is that awsvpc consumes one ENI per task, which can hit ENI density limits on smaller EC2 instance types faster than bridge mode would. For most production workloads handling sensitive data, that trade-off favors awsvpc's isolation; for very high-density, non-sensitive batch workloads on EC2, bridge may still be acceptable.
Take quiz
Shared security groups across all tasks on a host
Per-task security groups due to a dedicated ENI per task
Disabling all network traffic
Removing IAM roles
It cannot be used with Fargate
Higher ENI consumption, which can hit density limits on small instances
It removes support for load balancers
It requires host networking
50. How do you enable ECS Exec for debugging running containers?
ECS Exec lets you open an interactive shell or run a one-off command inside a running task's container, similar to kubectl exec, without SSH access to any host.
- Ensure the task role includes the
ssmmessagespermissions (CreateControlChannel,CreateDataChannel,OpenControlChannel,OpenDataChannel). - Enable Exec when creating the service or running the task:
--enable-execute-command. - Connect to a running container:
aws ecs execute-command \ --cluster my-cluster \ --task <task-id> \ --container app \ --interactive \ --command "/bin/sh"
Under the hood, it tunnels through AWS Systems Manager Session Manager, so no inbound ports need to be opened and all session activity can be logged to CloudWatch or S3 for auditing. It's intended for troubleshooting, not as a routine deployment mechanism.