Study guide
Technical reference and lesson notes
Purpose of This Lesson
This lesson demonstrates the core workflow for running a Docker container on Amazon Elastic Container Service (Amazon ECS) using AWS Fargate:
- Create an ECS cluster.
- Define the container and its runtime requirements in a task definition.
- Run an individual task or deploy a long-running ECS service.
- Configure networking, security groups, logging, and optional load balancing.
- Clean up the resources after testing.
The same concepts are important for SAP-C02 questions involving container orchestration, serverless compute, service availability, and operational design.
Key Concepts
Amazon ECS and launch types
Amazon ECS is a managed container orchestration service. It schedules and manages containers represented as ECS tasks.
ECS supports several compute options:
- AWS Fargate: Serverless compute for containers. AWS manages the underlying infrastructure, including the container host fleet.
- Amazon EC2 launch type: You manage the EC2 instances that provide capacity for ECS tasks, including instance scaling, patching, and capacity planning.
- ECS Anywhere: Allows ECS task management on customer-managed or external infrastructure.
Fargate is generally the simplest option when the requirement is to run containers without managing servers. It does not mean that the application is automatically highly available, load balanced, or autoscaling; those capabilities must be designed separately.
ECS clusters
An ECS cluster is a logical grouping for tasks and services. With Fargate, the cluster does not require customer-managed container instances. With the EC2 launch type, the cluster is associated with EC2 capacity or capacity providers.
Creating or deleting an empty ECS cluster does not normally create the main compute cost. Charges come from resources such as running Fargate tasks, load balancers, NAT gateways, logging, and data transfer.
Task definitions
A task definition is a versioned blueprint for running one or more containers. It can specify:
- Container image, such as
nginx:latest - CPU and memory allocation
- Container and host port mappings
- Environment variables and secrets
- IAM roles
- Logging configuration
- Health checks
- Storage and volume mounts
- Networking mode and runtime settings
A task definition is not itself a running container. It must be used to launch a task or create an ECS service.
For Fargate, task definitions use the awsvpc network mode. Each task receives its own elastic network interface and private IP address in the selected subnet.
Task execution role versus task role
These two IAM roles have different purposes:
| IAM role | Used by | Typical permissions |
|---|---|---|
| Task execution role | ECS/Fargate infrastructure while starting the task | Pull images from Amazon ECR, send logs to CloudWatch Logs, retrieve referenced secrets or parameters when configured |
| Task role | The application container itself | Call AWS APIs, such as reading from Amazon S3 or publishing to Amazon SNS |
Grant the task role only the permissions required by the application. Do not use the task execution role as a substitute for the application task role.
Running a task versus creating a service
An individual ECS task is useful for short-lived jobs, testing, or one-off commands. If the task stops, ECS does not automatically replace it unless another controller is configured.
An ECS service is used for long-running applications. It maintains a desired number of task replicas and replaces failed or stopped tasks. A service can also integrate with:
- Application Load Balancers or Network Load Balancers
- Service discovery
- Deployment configuration and circuit breakers
- Service Auto Scaling
- Capacity providers
For example, setting a desired count of two asks ECS to maintain two running task replicas. This alone does not guarantee that the replicas are distributed across Availability Zones or that users can reach them through a stable endpoint.
Fargate networking
Fargate tasks run inside a VPC subnet and use security groups. When launching a task, you select:
- VPC
- One or more subnets
- Security groups
- Whether to assign a public IP address
A task in a public subnet generally needs a public IP and a route to an internet gateway for direct inbound internet access. The security group must also allow the required inbound port, such as TCP 80.
For production workloads, a common design is:
- Place Fargate tasks in private subnets.
- Place an Application Load Balancer in public subnets.
- Permit inbound traffic to the load balancer from approved clients.
- Permit task traffic only from the load balancer security group.
- Provide NAT gateway access, VPC endpoints, or both for required outbound AWS and external connectivity.
A public subnet alone does not make a task reachable. Routing, public IP assignment, security group rules, network ACLs, and application listening configuration must all be correct.
Logging with Amazon CloudWatch Logs
Configure the awslogs log driver in the task definition to send container standard output and error streams to CloudWatch Logs. This improves troubleshooting and provides centralized operational visibility.
The task execution role needs permission to create log streams and publish log events when the configuration requires it. In production, define log group retention rather than keeping logs indefinitely by default.
Image selection
An image such as nginx:latest is convenient for a demonstration, but mutable tags are risky in production. Prefer immutable version tags or image digests so that task deployments are reproducible and auditable.
Images can be stored in:
- Amazon ECR: Private AWS container registry with IAM integration and vulnerability scanning options.
- Public registries: Require suitable network access and may introduce availability, rate-limit, and supply-chain considerations.
Exam-Relevant Takeaways
- Choose Fargate when you want ECS containers without managing EC2 instances.
- Choose ECS on EC2 when you need host-level control, specialized instance types, custom agents, or potentially different cost characteristics at sustained utilization.
- Use an ECS task definition to describe how containers run.
- Use an ECS task for a one-off or short-lived execution.
- Use an ECS service to maintain a desired number of continuously running tasks.
- A service can replace unhealthy or stopped tasks, but application health checks and deployment settings must be configured appropriately.
- A task role grants permissions to the application. A task execution role grants permissions needed to start and operate the task infrastructure.
- Fargate tasks use
awsvpcnetworking and receive task-level network interfaces and security groups. - Public IP assignment is not a replacement for proper security-group and route-table design.
- For internet-facing production services, prefer an ALB in public subnets with Fargate tasks in private subnets.
- Service Auto Scaling changes the desired task count; it does not replace infrastructure-level scaling concerns for EC2 launch type.
- Fargate task availability depends on the selected subnets, Availability Zones, quotas, image availability, and networking configuration.
Architecture Decision Guide
| Requirement | Recommended design | Reason |
|---|---|---|
| Run one container for a test or batch action | Run an ECS task on Fargate | Minimal orchestration and no server management |
| Keep a web application running continuously | ECS service on Fargate | Maintains the desired task count |
| Expose a production web service | ECS service behind an Application Load Balancer | Stable endpoint, health checks, and distribution across tasks |
| Keep containers isolated from direct internet traffic | Tasks in private subnets; ALB in public subnets | Reduces direct attack surface |
| Application reads from S3 | Assign a narrowly scoped ECS task role | Permissions are available to the application without embedding credentials |
| Pull a private ECR image | Configure the task execution role and network access | Fargate needs registry authentication and image-download access |
| Control the underlying hosts or use specialized EC2 capacity | ECS with EC2 capacity providers | Provides host and instance-level control |
| Scale task count based on CPU, memory, or request metrics | ECS Service Auto Scaling | Adjusts service desired count using CloudWatch metrics or policies |
| Run the same image consistently across deployments | Use immutable image tags or digests | Avoids unexpected changes caused by mutable tags |
Common Exam Traps
- Confusing a cluster with compute capacity: A Fargate cluster is a logical ECS grouping; it is not a pool of EC2 instances that you must patch.
- Assuming a task is self-healing: An individual task is not equivalent to a service. Use an ECS service for replacement and desired-count management.
- Mixing up IAM roles: The task role is for application API calls. The task execution role is for ECS/Fargate startup and operational actions.
- Assuming Fargate automatically provides high availability: Deploy multiple tasks across multiple Availability Zones and place them behind a load balancer when required.
- Using a public IP as the production architecture: Publicly addressable tasks increase exposure. Private subnets plus a load balancer are usually more appropriate.
- Forgetting outbound connectivity: Tasks may need access to ECR, CloudWatch Logs, Secrets Manager, or external services. Private-subnet designs require NAT gateways or suitable VPC endpoints, depending on the destination.
- Treating the security group as optional: The task must have a security group that allows required inbound and outbound traffic.
- Using
latestfor controlled releases: The tag can point to different image content over time. - Assuming service autoscaling is enabled automatically: Configure scaling policies, target metrics, cooldown behavior, and minimum and maximum task counts.
- Deleting only the service and expecting all resources to disappear: Load balancers, target groups, log groups, ECR repositories, NAT gateways, and CloudFormation stacks may require separate cleanup.
Real-World Engineer Notes
- Use at least two subnets in different Availability Zones for a production ECS service.
- Configure container health checks in addition to load balancer target health checks where appropriate. They validate different parts of the application path.
- Use AWS Secrets Manager or Systems Manager Parameter Store for sensitive configuration instead of plaintext environment variables.
- Set CPU and memory values based on measured workload behavior. Incorrect sizing can cause task placement failures, throttling, or unnecessary cost.
- Define CloudWatch log retention and alarms for task failures, unhealthy targets, elevated latency, and insufficient running task count.
- Use deployment circuit breakers, rollback settings, and minimum healthy percentage controls for safer ECS service deployments.
- Consider Fargate Spot for interruptible workloads, but do not use it as the only capacity for workloads that require uninterrupted availability.
- Fargate tasks are billed for requested task resources and runtime, subject to the applicable platform and pricing model. Stopping test tasks is important for cost control.
- If a task remains in
PENDING, inspect events and stopped-task reasons. Common causes include invalid subnet or security-group configuration, missing IAM permissions, unavailable image access, insufficient quotas, and inability to reach required endpoints. - Use infrastructure as code for repeatable clusters, task definitions, services, IAM policies, networking, and logging. Console-created resources are useful for learning but harder to audit and reproduce.
Quick Reference Summary
- Cluster: Logical ECS grouping.
- Task definition: Versioned container blueprint.
- Task: Running instance of a task definition.
- Service: Maintains a desired number of long-running tasks.
- Fargate: Serverless ECS compute; no customer-managed container hosts.
- Task execution role: Used to pull images, publish logs, and perform startup-related actions.
- Task role: Used by application code to call AWS APIs.
awsvpc: Fargate networking mode; each task receives task-level networking.- Public test deployment: May use a public subnet, public IP, and restricted security group.
- Production web deployment: Usually ALB in public subnets and tasks in private subnets.
- Cleanup: Stop tasks, delete services, then remove the cluster and any separately provisioned resources.
Flashcards
- Q: What problem does AWS Fargate solve for ECS users?
A: It runs ECS tasks without requiring customers to provision, patch, or scale the underlying container hosts.
- Q: What is the purpose of an ECS task definition?
A: It describes the containers, images, resources, ports, roles, logging, and other settings required to run a task.
- Q: When should you use an ECS service instead of an individual task?
A: Use a service for a continuously running application that needs a desired task count and replacement of stopped tasks.
- Q: What does the ECS task execution role do?
A: It allows ECS/Fargate to perform actions such as pulling private images and sending logs to CloudWatch Logs.
- Q: What does the ECS task role do?
A: It grants the application in the container permission to call AWS APIs.
- Q: What network mode does Fargate use?
A: awsvpc, which provides each task with its own elastic network interface and security group association.
- Q: Does assigning a public IP automatically make a Fargate task accessible?
A: No. Routes, security-group rules, subnet configuration, and the application listener must also permit connectivity.
- Q: How does an ECS service maintain availability?
A: It attempts to maintain the configured desired count and launches replacement tasks when tasks stop or fail health checks.
- Q: What is a common production pattern for internet-facing Fargate applications?
A: An Application Load Balancer in public subnets forwarding to Fargate tasks in private subnets.
- Q: Why are immutable image tags or digests preferred over
latest?
A: They make deployments predictable and prevent the same task definition from silently using different image content.
Practice Questions
Question 1
A company needs to run a stateless HTTP API on Amazon ECS. The API must remain available if a task fails, and clients need a stable endpoint. The company does not want to manage EC2 instances. Which design best meets these requirements?
A. Run one ECS task on Fargate with a public IP address
B. Run an ECS service on Fargate across multiple Availability Zones behind an Application Load Balancer
C. Run one ECS task on an EC2 launch-type cluster
D. Run the API as an AWS Lambda function without an API endpoint
Correct answer: B
Explanation: Fargate removes host management, while an ECS service maintains the desired task count. Multiple Availability Zones improve resilience, and the ALB provides a stable endpoint and health-based routing.
Question 2
A Fargate container must read objects from an S3 bucket. Which configuration should be used?
A. Add S3 permissions to the task execution role only
B. Add the S3 permissions to the ECS task role
C. Store an IAM user access key in the container image
D. Add S3 permissions to the security group
Correct answer: B
Explanation: The task role supplies temporary AWS credentials to application code running in the container. Security groups control network traffic and do not grant IAM permissions.
Question 3
A Fargate task in a private subnet cannot start because it cannot pull its image from a private Amazon ECR repository or publish logs to CloudWatch Logs. Which two areas should the architect investigate first? (Choose two.)
A. The task execution role permissions
B. Network egress through NAT or required VPC endpoints
C. An EC2 Auto Scaling group in the ECS cluster
D. An IAM policy attached to the ALB
E. A public IP on the task, which is mandatory for all Fargate tasks
Correct answer: A and B
Explanation: The execution role must permit image retrieval and log publishing. The private subnet must also provide connectivity to the required AWS endpoints through NAT gateways or appropriate VPC endpoints. EC2 capacity is not required for Fargate, and public IPs are not mandatory.
Question 4
An engineer launches an individual Fargate task for a web server. The task stops unexpectedly, and no replacement starts. The requirement is to keep two replicas running continuously. What should the engineer do?
A. Create an ECS service with a desired count of two
B. Increase the task definition memory only
C. Assign a second public IP to the stopped task
D. Create another ECS cluster
Correct answer: A
Explanation: An ECS service maintains the desired number of long-running tasks and replaces tasks that stop. A second cluster or additional public IP does not provide task replacement.
Question 5
A team wants repeatable deployments but currently uses the nginx:latest image tag in its ECS task definition. What is the most appropriate improvement?
A. Increase the ECS cluster size
B. Use an immutable version tag or image digest
C. Assign the task a public IP address
D. Disable CloudWatch logging
Correct answer: B
Explanation: Mutable tags can point to changing image content. Immutable tags or digests make deployments deterministic and easier to audit and roll back.