

# Amazon ECS Express Mode
Amazon ECS Express Mode

An Amazon ECS Express Mode service reduces the complexity of deploying containerized applications by providing sensible defaults and automating the configuration of supporting AWS services. Instead of managing configuration parameters across multiple services, an Express Mode service requires only three things to get started:
+ A container image
+ A task execution role
+ An infrastructure role

Amazon ECS Express Mode orchestrates and configures all necessary infrastructure: a Fargate-based ECS service with a unique accessible URL, load balancer with SSL/TLS, auto scaling policies, monitoring, and networking components.

Use Amazon ECS Express Mode services in the following scenarios:
+ Web applications and APIs - Stateless containerized applications that serve HTTP requests
+ Rapid prototyping - Quickly deploy and test applications without infrastructure setup overhead
+ Developer productivity - Enable application teams to deploy independently without deep AWS knowledge
+ Platform team efficiency - Reduce maintenance overhead by providing self-service deployment capabilities

Amazon ECS Express Mode services support either public or private HTTPS applications and automatically scale based on utilization or traffic.

## Benefits of Amazon ECS Express Mode services


Amazon ECS Express Mode services provide several key advantages for deploying and managing containerized applications on AWS.
+ Simplified deployment - Deploy containerized applications with production-ready defaults across multiple AWS services.
+ No compromise on capabilities - All underlying AWS resources remain accessible for direct management when you need fine-grained control or advanced features.
+ Cost optimization - Shares Application Load Balancers across multiple Express Mode services using the same networking configuration to reduce costs.
+ Transparent infrastructure - All resources are created in your AWS account with full visibility and accessibility through the AWS console and APIs.

## Pricing


There is no additional charge for using an Amazon ECS Express Mode service. You pay only for the underlying AWS resources that are created to run your application, including:
+ Fargate compute resources
+ Application Load Balancer
+ CloudWatch logs and metrics
+ Data transfer charges

## Availability


Amazon ECS Express Mode is available in all AWS Regions where Amazon ECS and Fargate are supported. You can create and manage Express Mode services using any of the following:
+ The Amazon ECS console
+ AWS AWS CLI
+ AWS SDKs
+ CloudFormation
+ Terraform
+ AWS Labs MCP Server for Amazon ECS

# Creating an Amazon ECS Express Mode service
Creating an Express Mode service

An Amazon ECS Express Mode service reduces the complexity of deploying containerized applications by providing sensible defaults and automating the configuration of supporting AWS services. Instead of managing configuration parameters across multiple services, an Express Mode service requires only a container image, task execution role and infrastructure role to get started.

After your deployment completes you will be returned a unique URL for your application. You can find the service you just deployed in *Clusters*, and if you did not specify a cluster it will be in the `Default` cluster.

## Prerequisites


Before creating an Express Mode service, ensure you have one of the following:
+ A container image stored in Amazon ECR.
+ Or a container image stored in a private registry. To use a private registry, configure a Secrets Manager secret. For more information, see [Create an AWS Secrets Manager secret](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html) in the *AWS Secrets Manager User Guide*.

**Note**  
IAM Roles are also required, but is covered in the [Console](express-service-first-run.html) and [CLI](express-service-getting-started.html) guides separately. The Amazon ECS Console has automated flows for role creation.

## Walkthroughs

+ For a simplified first-run experience using the console, see [Create your first Amazon ECS Express Mode service in the console](express-service-first-run.md).
+ To create an Express Mode service using the AWS CLI, see [Create your first Express Mode service using the AWS CLI](express-service-getting-started.md).
+ To learn more about what Express Mode creates and how it works, see [Resources created by Amazon ECS Express Mode services](express-service-work.md).

## Customizing


 When creating an Express Mode service, Amazon ECS selects defaults for your Amazon ECS and other AWS resources. Customize the application when needed by using the optional parameters. Take advantage of an Express Mode service and customize the following:
+ Service name
+ Amazon ECS Cluster
+ Container settings - port and health check path
+ Environment variables and secrets
+ Custom commands
+ Task role - This role allows your application code (on the container) to use other AWS services.

  You need this role when your application accesses other AWS services, such as Amazon S3.
+ Compute resources - CPU and memory allocation
+ Network configuration - subnets and service security group
+ Application Auto Scaling policies - metrics, target values, and task limits
+ CloudWatch Logs configuration
+ Resource tags

# Create your first Amazon ECS Express Mode service in the console
Create your first Express Mode service in the console

The console experience for Express Mode service provides a streamlined way to deploy your containerized application with minimal configuration required. Read more about prerequisites in [Amazon ECS Express Mode](express-service-overview.md). To learn more about what Express Mode creates and how it works, see [Resources created by Amazon ECS Express Mode services](express-service-work.md).

## Procedure


1. Open the console at [https://console.aws.amazon.com/ecs/v2](https://console.aws.amazon.com/ecs/v2).

1. In the navigation pane, choose **Express mode**.

1. Under **Let's set up your app**:

   1. Specify the image to use for your application. For **Image URI**, enter the URI for your image. To browse your Amazon ECR images, choose **Browse ECR images**, and then do the following:

      1. For **Private repository**, choose the Amazon ECR private repository.

      1. For **Image**, choose your image.

      1. Choose how to identify the image. For **Select image by**, choose one of the following options:
         + AWS recommends that you choose **Image digest**.
         + To use the tag, choose **Image tag** and then choose the tag.

   1. If using a private registry, select **Private registry**. Then for **Secrets Manager ARN or name**, enter the Secrets Manager ARN you created in the prerequisites.

   1. For **Task execution role**, and **Infrastructure role**, choose the roles. If you've never created these roles in Amazon ECS before, you will see the option to **Create new role** in the drop down. When you select this option, the role will be created for you automatically once you click **Create**. For the **Task execution role**, the Permission details will display the link for additional details on the [AmazonECSTaskExecutionRolePolicy](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSTaskExecutionRolePolicy.html) in the AWS Managed Policy Reference Guide. For the **Infrastructure role**, the Permission details will display the link for additional details on the [AmazonECSInfrastructureRoleforExpressGatewayServices](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRoleforExpressGatewayServices.html) Managed Policy in the AWS Managed Policy Reference Guide. 

      If you prefer to customize these roles, the **Create new role** button directs you to the IAM console where you can create the role, view, and edit the permissions attached to role. When you return to the Amazon ECS Express Mode console, refresh to view the role you created.
**Note**  
The first time you create a service in the Amazon ECS Console, some users may see an `Invalid Parameter Exception: Unable to assume the service linked role. ` If this occurs, wait a few seconds and try again.

1. Choose **Create**. You've just created your first Amazon ECS Express Mode service\$1

## Next steps


After creating your first Express Mode service:
+ Access your application using the provided Application URL once the deployment is complete.
+ Monitor deployment progress in the Resources tab of the console. When the deployment is complete, your service is ready to receive traffic. For more information, see [Viewing the details of an Amazon ECS Express Mode service](express-service-view-service.md).
+ To navigate back to your service, select from the navigation **Clusters**, then select the `default` Cluster if you did not specify one during the create. Amazon ECS Organizes services into logical groupings called clusters. This is an easy way to organize applications in your account.
+ If you encounter any issues during deployment, see [Troubleshooting Amazon ECS Express Mode services](express-service-troubleshooting.md).

## Customize


Optionally, you can also customize the configuration of your Express Mode service. Open the section titled **Additional configurations - *optional***.

1. Select a **Cluster** from the drop down if there is a specific Amazon ECS Cluster where you want to deploy your service. If no cluster is specified, Express Mode will use the `Default` cluster. If you leave the Express Mode console to create a cluster, use the refresh button to populate the drop down.

1. Enter a **Name** for the service. If no name is specified, Express Mode will generate one from the container image name. This service name will be used across several resources, including the Application URL, Amazon ECS Service, Amazon ECS Task Definition, certificate, scaling target, and scaling policy.

1. Optionally specify details about your **Container**:

   1. For **Container port**, enter the port your application listens on (default is 80).

   1. For **Health check path**, enter the path for health checks (for example, `"/health"`). The default is `"/".`

   1. Under **Environment variables**, add key-value pairs for environment variables your application needs. For **Key**, enter the environment variable name. For **Value type**, choose **Environment variable** or **Secret**. For **Value or value from**, enter the value or reference. Choose **Add environment variable** to add more variables as needed. No defaults are provided.

   1. For **Command**, optionally enter a custom command to override the Docker `CMD` instruction. No default is provided.

   1. For **Task role**, choose an IAM role that grants permissions to your application. No default is provided.

1. Optionally specify details about your **Compute** and **Auto scaling**:

   1. For **CPU**, choose the vCPU allocation for your tasks (the default is 1 vCPU).

   1. For **Memory**, choose the Memory allocation for your tasks (the default is 2 GB).

   1. For **ECS service metric**, choose the metric to scale on (the default is **Average CPU Utilization**).

   1. For **Target value**, choose the target percentage for scaling (the default is **60**.)

   1. For **Minimum number of tasks** and **Maximum number of tasks**, set the scaling limits. (The defaults are **1** and **20**)

1. Check the box to **Customize networking configurations**. If you do not customize these configurations, Express Mode will use the Default VPC.

   1. Select a **VPC** to help quickly navigate to the **Subnets** where your services will run. Optionally, leave the Amazon ECS Console to create a new VPC, and come back to refresh and find that VPC in the drop down.

   1. For **Security groups**, choose or create security groups to allow additional inbound network access to your service.

1. Under **Logs**:

   1. For **Amazon CloudWatch log group**, enter the preferred log group name for your application logs. The default log group is named according to your cluster and service names.

   1. For **Amazon CloudWatch log stream prefix**, enter a preferred prefix for log streams. The default stream prefix is `ecs/Main/.`

1. Under **Tags**, add key-value pairs to tag your resources. For **Key**, enter the tag key. For **Value**, enter the tag value. Choose **Add new item** to add more tags as needed. Tags can only be added on create.

# Create your first Express Mode service using the AWS CLI
Create your first Express Mode service using the AWS CLI

This tutorial shows you how to create an Express Mode service application using the AWS AWS CLI. You'll deploy a simple web application that demonstrates the core capabilities of Express Mode service.

## Prerequisites


Before you begin, ensure you have:
+ An AWS account with appropriate permissions
+ The AWS AWS CLI installed and configured
+ A container image stored in Amazon ECR or a private registry

## Step 1: Create IAM Roles


An Express Mode service requires two IAM roles. The Task Execution Role allows Amazon ECS to pull container images and write logs on your behalf. Create a task execution role and infrastructure role with the following policies:

```
#Create the roles with ECS trust policies
aws iam create-role --role-name ecsTaskExecutionRole \
    --assume-role-policy-document '{
        "Version": "2012-10-17",		 	 	 
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {
                    "Service": "ecs-tasks.amazonaws.com"
                },
                "Action": "sts:AssumeRole",
            }
        ]
    }'

aws iam create-role --role-name ecsInfrastructureRoleForExpressServices \ 
    --assume-role-policy-document '{
        "Version": "2012-10-17",		 	 	 
        "Statement": [
            {
                "Sid": "AllowAccessInfrastructureForECSExpressServices",
                "Effect": "Allow",
                "Principal": {
                    "Service": "ecs.amazonaws.com"
                },
                "Action": "sts:AssumeRole"
            }
        ]
    }'
```

```
#Attach the AWS managed policies
aws iam attach-role-policy --role-name ecsTaskExecutionRole \
    --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
aws iam attach-role-policy --role-name ecsInfrastructureRoleForExpressServices \
    --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSInfrastructureRoleforExpressGatewayServices
```

For more information, see [Amazon ECS task execution IAM role](task_execution_IAM_role.md).

## Step 2: Create your first Express Mode service application


Create an Express Mode service application with the minimum required parameters:

```
aws ecs create-express-gateway-service \
    --primary-container "image"="public.ecr.aws/nginx/nginx:latest" \
    --execution-role-arn arn:aws:iam::123456789012:role/ecsTaskExecutionRole \
    --infrastructure-role-arn arn:aws:iam::123456789012:role/ecsInfrastructureRoleForExpressServices \
    --monitor-resources
```

This command creates an Express Mode service application with:
+ A unique service name generated from the image name
+ 1 vCPU and 2 GB memory
+ Port 80 for HTTPS traffic
+ Auto scaling based on CPU utilization
+ An internet-facing Application Load Balancer in the default VPC and public subnets
+ A URL unique to this service in the format `servicename.ecs.region.on.aws`

The command continuously monitors resources as they are being provisioned and returns status. Once the service deployment is complete, the Application URL is ready to receive traffic. When you interrupt the monitoring, the information about the created service is returned, including the service ARN and URL:

```
{
    "service": {
        "cluster": "arn:aws:ecs:region:123456789012:cluster/default",
        "serviceName": "nginx-1234",
        "serviceArn": "arn:aws:ecs:region:123456789012:service/default/nginx-1234",
        "infrastructureRoleArn": "arn:aws:iam::123456789012:role/ecsInfrastructureRoleForExpressServices",
        "status": {
            "statusCode": "ACTIVE"
        },
        "createdAt": "UNIXTIMESTAMP"
    }
}
```

## Step 3: Create an Express Mode service application with custom settings


You can customize your Express Mode service application by specifying additional parameters:

```
aws ecs create-express-gateway-service \
    --execution-role-arn arn:aws:iam::123456789012:role/ecsTaskExecutionRole \
    --infrastructure-role-arn arn:aws:iam::123456789012:role/ecsInfrastructureRoleForExpressServices \
    --primary-container '{"image":"123456789012.dkr.ecr.region.amazonaws.com/my-app:latest","containerPort":8080,"environment":[{"name":"ENV","value":"production"},{"name":"DEBUG","value":"false"}]}' \
    --service-name "my-web-app" \
    --cpu 2 \
    --memory 4 \
    --health-check-path "/health" \
    --scaling-target '{"minTaskCount":3,"maxTaskCount":100}' \
    --monitor-resources
```

This creates an application with:
+ A custom name "my-web-app"
+ 2 vCPU and 4 GB memory
+ Port 8080 for application traffic
+ Custom health check endpoint
+ Environment variables
+ Minimum 3 tasks, maximum 100 tasks for auto scaling

## Step 4: Monitor your deployment


The `--monitor-resources` flag works on any Create, Update or Delete call to your Express Mode services. But in addition, you can monitor the resources in a service at any time, separate from a mutating action. Deployment time can vary depending on the resources that need to be provisioned. Once the status changes to `ACTIVE`, your application is ready to receive traffic.

```
aws ecs monitor-express-gateway-service --service-arn arn:aws:ecs:region:123456789012:service/app-23d97h88
```

You can also find current configuration and status of your Express Mode service application:

```
aws ecs describe-express-gateway-service --service-arn arn:aws:ecs:region:123456789012:service/app-23d97h88
```

## Step 5: Access your application


Access the Express Mode service application using the provided URL when it becomes active. The URL format is:

```
https://<service-name>.ecs.<region>.on.aws/
```

For example:

```
https://app-23d97h88.ecs.us-west-2.on.aws/
```

Your application is now running with:
+ Automatic SSL/TLS termination
+ Load balancing across multiple Availability Zones
+ Auto scaling based on CPU utilization
+ CloudWatch logging and monitoring
+ 5XX Rollback Alarms and Canary Deployments for future updates 

# Resources created by Amazon ECS Express Mode services
Resources created by Express Mode services

An Express Mode service reduces the complexity of deploying containerized applications by providing sensible defaults and automating the configuration of supporting AWS services. Instead of managing hundreds of configuration parameters across multiple services, an Express Mode service requires only a container image, task execution role and infrastructure role to get started.

Express Mode services have simplified procedures for provisioning and configuring an Amazon ECS Service that bundles together the preferred infrastructure for getting a production web application running. Express Mode services automatically incorporate operational and configuration best practices. The following resources are created:
+ The ECS default cluster (if it does not already exist) with Fargate capacity providers
+ A task definition with container, logging, and networking configurations
+ A service with canary deployment and auto scaling
+ Application Load Balancer with HTTPS listener, listener rules, and target groups
+ Security groups with minimal required ingress
+ Service Linked Roles for auto-scaling and load balancing
+ Application Auto Scaling scalable target and target tracking scaling policy.

  The scaling policy adds or removes service tasks as required to keep the metric at, or close to, the specified target value. In addition to keeping the metric close to the target value, a target tracking scaling policy also adjusts to the fluctuations in the metric due to a fluctuating load pattern and minimizes rapid fluctuations in the number of tasks running in your service.
+ Log group specific to the service
+ Metric alarm for detecting faulty deployments
+ ACM certificate

Use the defaults to get started with Express Mode services, or configure your application using a minimal set of parameters. 

## Cluster defaults


The following defaults are configurable from within Express Mode for the Cluster:
+ clusterName: Uses the `default` cluster.

  You can customize this option by using the **Additional configurations** option in the console, or by specifying `create-express-gateway-service --cluster`.

The following defaults are set by Express Mode but can be updated in the Cluster directly.
+ capacityProviders: ["FARGATE"] - Uses Fargate

## Task definition defaults


The following defaults are configurable from within Express Mode for the task definition:
+ cpu: 1024 - 1 vCPU unit allocated to the task

  You can customize this option by using the **Additional configurations** option in the console, or by running `create-express-gateway-service --cpu`.
+ memory: 2048 - 2 GB of memory allocated to the task

  You can customize this option by using the **Additional configurations** option in the console, or by running `create-express-gateway-service --memory`.

The following defaults are set by Express Mode but can be updated in the Task Definition directly.
+ networkMode: "awsvpc" - Uses `awsvpc` networking mode
+ operatingSystemFamily: "LINUX" - Runs on Linux operating system
+ cpuArchitecture: "X86\$164" - Uses x86\$164 processor architecture
+ requiresCompatibilities: ["FARGATE"] - Compatible with Fargate launch type
+ platformVersion: "LATEST" - Uses the latest Fargate platform version

## Container definition defaults


The following defaults are configurable from within Express Mode for the container:
+ port: 80 - Default port for container traffic

The following defaults are set by Express Mode but can be updated in the Task Definition - Container Definition directly:
+ essential: true - Container is marked as essential for task health
+ protocol: "tcp" - Default protocol for load balancer communication
+ name: "Main" - Default name for the primary container

  Changing the name of the default container can effect Express Mode's ability to make subsequent updates to your service. This is not recommended if you intend to continue using the Express Mode Console or APIs
+ versionConsistency: enabled - Resolves image tags to digest IDs for consistent deployments
+ initProcessEnabled: true - Enables Docker init process support.
+ stopTimeout: 30 seconds - Time between SIGTERM and SIGKILL signals.

## Logging defaults


The following defaults are configurable from within Express Mode for the CloudWatch Logs:
+ awslogs-group: "/aws/ecs/<cluster>/<name>-\$1\$1\$1\$1" - Log group name derived from cluster and service name

  You can customize this option by using the **Additional configurations** option in the console, or by running `create-express-gateway-service --primary-container “awsLogsConfiguration”=[{“logGroup”=“/my/logGroup/”}]`.
+ awslogs-stream-prefix: "ecs" - Prefix for log stream names

  You can customize this option by using the **Additional configurations** option in the console, or by running `create-express-gateway-service --primary-container “awsLogsConfiguration”=[{“logStreamPrefix”=“myprefix”}]`.

The following defaults are set by Express Mode but can be updated in the Task Definition - Log Configuration directly:
+ logDriver: "awslogs" - Uses CloudWatch Logs
+ awslogs-region: current Region - Uses the same Region as the Express Mode service
+ mode: "non-blocking" - Logging mode set to non-blocking
+ max-buffer-size: "25m" - Maximum buffer size for log writes

## Service defaults


The following defaults are configurable from within Express Mode for the Amazon ECS Service:
+ serviceName: Express Mode service → Name - Name of the service (customer provided or derived from the image name)

  Name can only be configured on create, and is not available to be configured on updates.
+ cluster: Express Mode service → Cluster - ECS cluster for this service (customer provided or default)

  Cluster can only be configured on create, and is not available to be configured on updates.
+ desiredCount: Express Mode service → MinTasks - Desired count for service (default is 1)

  You can customize this option by using the **Additional configurations** option in the console, or by running `create-express-gateway-service --scaling-target ‘{“minTaskCount”=3}',`
+ tags: Express Mode service Tags for AWS tagging (customer provided)

  You can customize this option by using the **Additional configurations** option in the console, or by running `create-express-gateway-service --tags`. Tags can only be added on the create of a new resource. 

The following defaults are set by Express Mode but can be updated in the Amazon ECS Service directly:
+ availabilityZoneRebalancing: true - Enables automatic AZ rebalancing
+ CapacityProviderStrategy: \$1"base": 1, "capacityProvider": "FARGATE", "weight": 1\$1 - Uses Fargate for compute capacity
+ deploymentConfiguration: Canary by default - Express Mode service uses Canary deployments

  Note that deployment strategy can not be updated on Express Mode services.
+ enableECSManagedTags: true - Enables ECS-managed resource tagging
+ healthCheckGracePeriodSeconds: 300 - Grace period before Scheduler looks at ELB or Lattice health checks (aligns with ELB health check grace period default)
+ launchType: <Not set> - Uses capacity providers 
+ loadBalancers: Load balancer configuration handled by ECS

  Note that load balancer configurations can not be updated on Express Mode services.
+ placementStrategy: Not set - Uses Fargate at launch (should always be AZ Spread)
+ platformVersion: LATEST - Fargate platform version (hard coded to LATEST)
+ propagateTags: "SERVICE" - Propagates tags from the service to tasks
+ schedulingStrategy: "REPLICA" - Express Mode services are REPLICA services
+ taskDefinition: Express Mode service created - The task definition to use (provided by Express Mode service)

## Network configuration defaults


The following defaults are configurable from within Express Mode for the Amazon ECS Service - Network Configuration:
+ networkConfiguration.Subnets: If none are provided, Express Mode will use the default public subnets in the default VPC.

  The default VPC must have at least two public subnets, in at least two availability zones, with at least 8 free IPs available, per assigned CIDR block, per subnet.

  If you provide custom public subnets, Express Mode will provision an internet-facing ALB and turn on assignPublicIP for your tasks. If you provide private subnets (subnets without an internet gateway in their route table), Express Mode will provision an internal ALB.

  If you specify subnets, the first Express Mode service for a VPC defines the subnets associated with either the internet-facing or internal load balancer for that VPC. Subsequent Express Mode services that launch in the same VPC must have subnets that match the availability zones supported by the load balancer. Because of this, we recommend creating Express Mode services with subnets from all availability zones.
+ networkConfiguration.SecurityGroups: If none are provided, Express Mode creates both a Service Security Group and a Load Balancer Security Group

  The Service Security Group allows outbound traffic to the public internet, but this may be restricted depending on other aspects of your networking, such as your subnet configuration.

  The Load Balancer Security Group The Load Balancer Security Group allows inbound traffic for HTTPS resolution and outbound traffic to your Service Security Group on the container port you specify (default 80). And is automatically updated to match the container port provided in your Express Mode Create or Update calls.

  You can customize this option by using the **Additional configurations** option in the console, or by running `create-express-gateway-service --network-configuration '{"securityGroup": ["sg-xxxxxxx"]}'`. When you provide a security group you are providing an additional ingress path to your service.

The following defaults are set by Express Mode but can be updated in the Amazon ECS Service - Network Configuration directly:
+ assignPublicIp: Based on subnet type - Enabled for public subnets to ensure users of the default VPC are able to access the public internet, we enable public IPs on each task by default. This is disabled if you provide a private subnet, and you are then responsible for configuring a NAT gateway if your tasks need internet access. 

## IAM role defaults


The following IAM roles are configurable for an Express Mode Service with automatic creation of service-linked roles where appropriate.
+ executionRoleArn: Task Execution Role (required parameter)

  While the required permissions are in the managed policy, additional policies and permissions can be attached. Additional details on the [AmazonECSTaskExecutionRolePolicy](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSTaskExecutionRolePolicy.html) in the AWS Managed Policy Reference Guide
+ infrastructureRoleArn: Infrastructure Role for Express Gateway Services (required parameter)

  While the required permissions are in the managed policy, additional policies and permissions can be attached. Additional details on the [AmazonECSInfrastructureRoleforExpressGatewayServices](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRoleforExpressGatewayServices.html) Managed Policy in the AWS Managed Policy Reference Guide
+ taskRoleArn: Task Role for calls from container application code (optional)

  You can customize this option by using the **Additional configurations** option in the console, or by running `create-express-gateway-service --task-role-arn`.

  You must create the new IAM role before you create or update the Express Mode service.

The following IAM roles are configured by Express Mode automatically.
+ ecsServiceRoleForECS: Allows Amazon ECS to manage your cluster
+ AWSServiceRoleForElasticLoadBalancing: Calls other AWS services for you on your behalf - created automatically by Elastic Load Balancing 
+ AWSServiceRoleForApplicationAutoScaling\$1ECSService: Calls other AWS services on your behalf - created automatically by Application Auto Scaling

## Application Auto Scaling defaults


The following Application Auto Scaling settings can be configured in Express Mode:
+ autoScalingTargetValue: 60 - Target CPU utilization percentage for scaling
+ autoScalingMetric: "CPUUtilization" - Metric used for auto scaling decisions
+ desiredMinTaskCount: 1 - Minimum number of tasks to maintain
+ desiredMaxTaskCount: 20 - Maximum number of tasks to scale to (can be increased or decreased)

The following settings can be conifgured in Application Auto Scaling directly:
+ policyType: "TargetTrackingScaling" - Uses target tracking scaling policy
+ disableScaleIn: false - Allows scaling down when demand decreases

## Application scaling target defaults


Application Auto Scaling targets define the scalable resource and capacity limits for automatic scaling operations. The following can be modified in Express Mode:
+ MaxCapacity: Express Mode service → MaxTasks - Maximum tasks the service will scale up to (default from CreateLoadBalancedService or customer provided)
+ MinCapacity: Express Mode service → MinTasks - Minimum tasks the service will scale down to (default from CreateLoadBalancedService or customer provided)
+ ScalableDimension: ecs:service:DesiredCount - The property to scale
+ Tags: Derived from the tags passed in CreateLoadBalancedService - Resource tags for this resource

The following defaults can be modified in Application Auto Scaling scalable target:
+ DynamicScalingInSuspended: false - Indicates if scaling in is suspended
+ DynamicScalingOutSuspended: false - Indicates if scaling out is suspended
+ ScheduledScalingSuspended: false - Indicates if scheduled scaling is suspended

## Application scaling policy defaults


Scaling policies implement target tracking algorithms that monitor CPU utilization and adjust task count to maintain optimal performance. The following can be modified from Express Mode:
+ TargetValue: 60% - The target value for the tracking policy (Express Mode service → scaling-target-value)
+ PredefinedMetricType: ECSServiceAverageCPUUtilization - The name type of metric being tracked (Express Mode service → scaling-metric)

  Express Mode provides scaling metrics for Average CPUUtilization, Average Memory Utilization, and Request Count per Target. Request Count per Target comes from the Application Load Balancer and can be set up to 65536 requests per target per second, which is your Amazon ECS Service in the Application Load Balancer target group.

The following defaults are set by Express Mode but can be changed in the Application Auto Scaling policy:
+ PolicyName: <ServiceName><"TargetMetric"> - Name of this scaling policy (derived from ECS Service name and Target Metric)
+ PolicyType: TargetTrackingScaling - The type of scaling being done (predefined default)
+ ScalableDimension: "ecs:service:DesiredCount" - The property to be scaled (predefined default)
+ DisableScaleIn: false - Indicates if scale in is disabled

## Application Load Balancer defaults


The following Application Load Balancer defaults can be configured in Express Mode:
+ scheme: depends on subnets - Creates an Internet-facing load balancer with public IP addresses when public subnets are provided. Creates an Internal load balancer with private IP addresses when private subnets are provided.
+ ip-address-type: depends on subnets - Creates an IPv4 only Application Load Balancer when addresses are IPv4. When there are IPv6-enabled subnets, a dual-stack Application Load Balancer will be created. Note that if you have IPv6-enabled subnets, the first Express Mode service in a VPC defines the internal or internet-facing load balancer for that VPC. Because of this, we recommend creating your IPv6-only subnets first, or in a new VPC. 

The following defaults are set in Express Mode and can be configured in Application Load Balancer:
+ desync-mitigation-mode: Off - HTTP desync mitigation is disabled
+ access-logs.enabled: false - Access logging is disabled
+ listener-configurations.protocol: https - Uses HTTPS protocol for secure communication
+ listener-configurations.port: 443 - Listens on standard HTTPS port
+ listener-configurations.rule-type: host-header - Routes traffic based on host header rules

## Target group defaults


The following Amazon EC2 Target Group defaults can be configured in Express Mode:
+ health-check-path: (default "/") Express Mode service health check path - URL path for health check requests
+ port: (default 80) - Port on which targets receive traffic
+ health-check-port: (default 80) - Port for health check requests

The following defaults are set by Express Mode and can be configured in Amazon EC2 Target Groups:
+ protocol: HTTP - Protocol for routing traffic to targets
+ protocol-version: HTTP1 - HTTP protocol version for communication
+ vpc-id: default is the default VPC - Virtual Private Cloud identifier for the target group, but will be derived from the subnets provided
+ health-check-protocol: Same as Protocol - Protocol for health check requests
+ health-check-enabled: Always enabled - Health checks are automatically enabled
+ health-check-interval-seconds: 30 - Time between health checks of individual targets
+ health-check-timeout-seconds: 5 - Timeout duration for health check responses
+ healthy-threshold-count: 5 - Consecutive successful health checks required for healthy status
+ unhealthy-threshold-count: 2 - Consecutive failed health checks required for unhealthy status
+ target-type: ip - Targets are registered by IP address
+ ip-address-type: ipv4 - Uses IPv4 addresses for target registration

## Resource sharing and cost optimization


Express Mode services automatically share resources when possible to optimize costs:
+ **Load balancer sharing** - Up to 25 Express Mode services in the same VPC can share an Application Load Balancer. Express Mode will provision additional Application Load Balancers as necessary depending on the amount of Express Mode services you have provisioned. And as you reduce the amount of Express Mode services in your VPC, Express Mode will also deprovision unused Application Load Balancers.This sharing reduces the effective cost per application as you deploy more Express Mode services.
+ **Cluster sharing** - Express Mode services can be grouped together in Amazon ECS Clusters. Express Mode services can also share Amazon ECS Clusters with Amazon ECS Services not managed by Express Mode.



# Viewing the details of an Amazon ECS Express Mode service
Viewing the details of an Express Mode service

You can view details about your Express Mode service to monitor its status, configuration, and performance metrics. The service details page provides comprehensive information about your service's current state, running tasks, deployment history, and operational metrics. 

**To view an Express Mode service (Amazon ECS console)**

1. Open the console at [https://console.aws.amazon.com/ecs/v2](https://console.aws.amazon.com/ecs/v2).

1. In the navigation pane, choose **Clusters**.

1. On the **Clusters** page, choose the name of the cluster that contains your Express Mode service.

1. On the cluster details page, choose the **Services** tab.

1. Configure a filter to view your Express Mode services. For **Filter resource management type**, choose **ECS**.

   An Express Mode service has a **Express** badge next to the name.

1. Select the name of your Express Mode service to navigate to the service detail page for your Express Mode service.

1. Review the service information displayed on the service details page:

   1. **Express service Overview** - View basic service information including Application URL, Service status, Pending and Running Tasks, and Active Deployments.

   1. **Observability** - View CloudWatch metrics for CPU Utilization (min, max, average) Memory Utilization (min, max, average), Target Response time (p50,p90,p99), RequestCount, 4xx Statuses and 5xx Statuses.

   1. **Logs** - View logs from the containers in your tasks.

   1. **Resources** - Your AWS Resources created for your Express Mode service. The Timeline view updates automatically after a Create or Update and shows status and events. The Table view provides a searchable table with the status and full ARNs for each resource.

   1. **Deployments** - Track deployment history and current deployment status, include the service revision and tasks which provide valuable information during updates. The events panel lets you know when your Express Mode service has reached a steady state.

   1. **Configuration** - View service configuration, including the cluster, roles, container configuration, compute, auto scaling and networking configuration.

   1. **Tags** - Manage your tags.

# Updating an Amazon ECS Express Mode service


The Express Mode service simplifies the service update process by providing configurable options for networking, load balancing, and Application Auto Scaling and orchestrating changes across these services.

You can update your Express Mode service to modify container images, adjust resource allocation, or change configuration settings. Updates are deployed using canary deployments with alarm based rollback alarms to maintain availability.

## Deployment behavior


An Express Mode service uses canary deployments by default to ensure safe updates and quick rollbacks:
+ A new environment is created and tasks deployed with your changes
+ 5% of traffic is shifted to the new environment
+ Alarm Based Rollbacks will trigger if sum of 4xx and 5xx errors percentage is > 1 for 2 datapoints within 3 minutes
+ Health checks verify the new tasks are healthy
+ After 3 minutes bake time, 100% of traffic is shifted to new environment
+ After 3 minutes bake time for monitoring, old tasks are gradually stopped and replaced

For more information, see [Amazon ECS canary deployments](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/canary-deployment.html)

## Procedure


1. Open the console at [https://console.aws.amazon.com/ecs/v2](https://console.aws.amazon.com/ecs/v2).

1. In the navigation pane, choose **Clusters**.

1. On the **Clusters** page, choose the name of the cluster that contains your Express Mode service.

1. On the cluster details page, choose the **Services** tab.

1. Configure a filter to view your Express Mode services. For **Filter resource management type**, choose **ECS**.

   An Express Mode service has a **Express** badge next to the name.

1. Under **Configuration**:

   1. Specify the image to use for your application. For **Image URI**, enter the URI for your image. To browse your Amazon ECR images, choose **Browse ECR images**, and then do the following:

      1. For **Private repository**, choose the Amazon ECR private repository.

      1. For **Image**, choose your image.

      1. Choose how to identify the image. For **Select image by**, choose one of the following options:
         + AWS recommends that you choose **Image digest**.
         + To use the tag, choose **Image tag** and then choose the tag.

   1. To use a private registry, select **Private registry**. Then, for **Secrets Manager ARN or name**, enter the Secrets Manager ARN you created in the prerequisites.

   1. For **Task execution role**, choose the roles or create a new role and refresh. You can update the task execution role when you need to add additional permissions.

1. Under **Additional configurations**, customize your service.

   1. Under **Container**:

      1. For **Container port**, update the port your application listens on (default is 80).

      1. For **Health check path**, update the path for health checks (for example, `/health`).

   1. Under **Environment variables**, add key-value pairs for environment variables your application needs:

      1. For **Key**, enter the environment variable name.

      1. For **Value type**, choose **Environment variable** or **Secret**.

      1. For **Value or value from**, enter the value or reference.

      1. Choose **Add environment variable** to add more variables as needed.

   1. For **Command**, optionally enter a custom command to override the Docker CMD instruction.

   1. For **Task role**, add an IAM role that grants permissions to your application running in your containers. This allows your application to make API calls to AWS services.

   1. Under **Compute**:

      1. For **CPU**, update the vCPU allocation for your tasks (for example, 1 vCPU).

      1. For **Memory**, update the memory allocation for your tasks (for example, 2 GB).

   1. Under **Auto Scaling**:

      1. For **ECS service metric**, choose the metric to scale on (for example, **ECS Service Average Memory Utilization** or **Request count per target**).

      1. For **Target value**, enter the target for scaling (for example, **60** or **1000**).

      1. For **Minimum number of tasks** and **Maximum number of tasks**, update the scaling limits.

   1. Under **Logs**:

      1. For **Amazon CloudWatch log group**, update the log group name for your application logs. Note this will not move existing logs, but begin writing logs from the new service revision.

      1. For **Amazon CloudWatch log stream prefix**, enter a new prefix for log streams.

1. Choose **Update** to update your Express Mode service.

# Delete Amazon ECS Express Mode services
Delete Express Mode services

When you delete an Express Mode service, you remove the service and delete its associated resources including the cluster, load balancer, and other infrastructure components.

**Important**  
Deleting an Express Mode service will stop all running tasks and make your application unavailable. This action cannot be undone.

The following resources may be deleted depending on your selection:
+ The Amazon ECS cluster (if no other services are running)
+ The Amazon ECS service, task definition, and any running tasks
+ Service security group
+ CloudWatch log group
+ Metric alarm
+ ACM Certificate
+ The Application Load Balancer (if no other services are configured), target group, security group, listener, and listener rule
+ Auto Scaling policy, scalable target

Consider the following::
+ Ensure you have backed up any important data before deletion
+ Consider scaling the service to zero tasks before deletion to gracefully stop traffic
+ Review dependencies that might be affected by the deletion

## Difference between deleting an Express Mode service and a service


When you delete a service, Amazon ECS will delete the service if there are no running tasks. Amazon ECS does not delete target groups associated with the service or the default cluster (if it was used). When you delete an Express Mode service, Amazon ECS will delete the service as well as any resources that are distinct to the Express Mode service service. For example, if the Express Mode service service created the load balancer and is the only service using the load balancer it will delete the associated load balancer. If the load balancer is being shared, even with resources not managed by Express Mode, it will not be deleted.

## Procedure


1. Open the console at [https://console.aws.amazon.com/ecs/v2](https://console.aws.amazon.com/ecs/v2).

1. On the **Clusters** page, select the cluster for the service.

1. On the **Clusters** page, choose the cluster.

1. Choose the **Services** tab.

1. Select the services to delete.

1. Choose **Delete**.

1. In the **Delete confirmation** dialog box:

   1. Enter **delete** to confirm the deletion.

1. Choose **Delete** to confirm.

1. Stay on the page to monitor deletion progress and view a list of resources that have been removed, as well as those that have been retained and may require manual cleanup.

# Best practices for Amazon ECS Express Mode services
Best practices for Amazon ECS Express Mode services

Learn about best practices and recommendations for using Express Mode service effectively in production environments.

## Security best practices


### Secrets management

+ **Use Secrets Manager for secrets** - Store sensitive data in Secrets Manager (e.g. private repository or database credentials).

  For more information Secrets Manager best practices, see [Secrets Manager best practices](secretsmanager/latest/userguide/best-practices.html) in the *Secrets Manager User Guide*
+ **Enable encryption at rest** - Ensure secrets are encrypted when stored in AWS services.

  Using a service such as Secrets Manager allows you to encrypt using either an AWS managed or customer provided key.
+ **Implement secret rotation** - Use automatic rotation for database passwords and API keys.

  Using a service such as Secrets Manager can manage secret rotation for services like Amazon Aurora and Amazon RDS

Example of using secrets in Express Mode service:

```
aws ecs update-express-gateway-service \
    --primary-container \
        ‘{“environment”=[{“name”=“DB_PASSWORD”,”value”=“arn:aws:secretsmanager:us-west-2:123456789012:secret:prod/db/password”}, \
        {“name”=“API_KEY”,”value”=“arn:aws:ssm:us-west-2:123456789012:parameter/prod/api-key”}]}’ \
```

### Network security

+ **Use private subnets for sensitive applications** - Deploy applications that don't need direct internet access in private subnets.

  For more information on recommended architectures, refer to [Connect Amazon ECS application to the internet.](AmazonECS/latest/developerguide/networking-outbound.html)
+ **Configure security groups to be minimally permissive** - Restrict inbound and outbound traffic to only necessary ports and sources.

  To restrict the outbound traffic of the Express Mode Service Security Group, you can edit this directly in Amazon EC2 Security Groups Console by modifying the Outbound rules, or use the following commands: 

  ```
                      
  aws ec2 authorize-security-group-egress
      --group-id sg-xxxxxxxx \
      --protocol tcp \ 
      --port 443 \ 
      --cidr 0.0.0.0/0
  
  aws ec2 revoke-security-group-egress
      --group-id sg-xxxxxxxx \
      --protocol tcp \
      --port 443 \ 
      --cidr 0.0.0.0/0
  ```
+ **Enable Amazon VPC Flow Logs** - Monitor network traffic for security analysis and troubleshooting.

  You can enable this in each subnet in use by your Express Mode applications in the VPC Subnet Console, or use ` aws ec2 create-flow-logs --resource-ids subnet-xxx`
+ **Use AWS WAF for web applications** - Protect against common web exploits and attacks.

  You can enable this by creating a Web ACL and then associating it to the Application Load Balancer used by your Express Mode service. In Console, Create a web ACL in the WAF & Shield Service and associate to your Application Load Balancer. Or, use `aws wafv2 create-web-acl` and `aws wafv2 associate-web-acl --resource-arn <alb>`.

## Performance and Compute optimization


### Resource sizing

+ **Right-size CPU and memory** - Monitor application performance and adjust CPU and memory allocations based on actual usage patterns.

  AWS Compute Optimizer generates recommendations for Amazon ECS task and container sizes. For more information, see [What is AWS Compute Optimizer?](https://docs.aws.amazon.com/compute-optimizer/latest/ug/what-is-compute-optimizer.html) in the *AWS Compute Optimizer User Guide*.
+ **Performance test your application** - To ensure your application operates at scale and with the given scaling thresholds and resources allocations, perform load testing.

### Auto scaling configuration

+ **Set appropriate scaling thresholds** - Configure CPU or memory thresholds that trigger scaling before performance degrades.

  You can modify the service metric's target value in your Express Mode service console. 

  Consider adding a predictive scaling policy, especially if your traffic follows a time-based pattern. See [ Predictive Auto Scaling](AWSEC2ContainerServiceDocs/latest/shared/predictive-auto-scaling.html) for more information.
+ **Use multiple scaling metrics** - Consider using both CPU or Memory and request-based scaling for more responsive scaling.

  You can add multiple policies to a service. Express Mode adds one by default, but you can attach addtional policies to your service directly.
+ **Configure minimum and maximum limits of tasks** - Set reasonable bounds to control costs and ensure availability.

  For production workloads, once initial testing is complete - we recommend running in three availability zones to follow availability best practices. You can update the **Minimum number of tasks ** in the Express Mode Console, or by using `update-express-gateway-service --scaling-target '{“minTaskCount”=3}'`.

### Health checks

+ **Implement meaningful health checks** - Create health check endpoints that verify critical application dependencies.

  You can update the **Health check path** in the Express Mode Console. Or by using `update-express-gateway-service --health-check-path "/health"`.

  For more information on forming health checks for your application, refer to [Implementing Health Checks](https://d1.awsstatic.com/builderslibrary/pdfs/implementing-health-checks.pdf)
+ **Keep health checks lightweight** - Avoid expensive operations in health check endpoints.

  Examples might include external API calls, CPU or memory intensive opeartions, or long running operations with the potention to timeout.
+ **Use appropriate timeouts** - Configure health check timeouts that allow for normal response times while detecting failures quickly.

  Health check timeouts for Express Mode can be configured on the Application Load Balancer target group. In the Amazon EC2 Console, Navigate to the **Target Groups** section and select your Express Mode target group. Select the **Health Checks** Tab and click **Edit**, under **Advanced health check settings** you can adjust the timeout. Or, use `aws elbv2 modify-target-group --target-group-arn <targetgroup> --health-check-timeout`.
+ **Return proper HTTP status codes** - Use 200 for healthy and 4xx/5xx for unhealthy states.

## Operational best practices


### Monitoring and logging

+ **Enable Enhanced Container Insights** - Use CloudWatch; Enhanced Container Insights for comprehensive monitoring of your Express Mode service applications.

  See [Setting up Container Insights on Amazon ECS](AmazonCloudWatch/latest/monitoring/deploy-container-insights-ECS-cluster.html) for more information.
+ **Set up custom metrics** - Publish application-specific metrics to CloudWatch; for business logic monitoring.

  See [Public custom metrics](AmazonCloudWatch/latest/monitoring/publishingMetrics.html) in the *CloudWatch User Guide* for more information.
+ **Configure log retention** - Set appropriate log retention periods to balance cost and compliance requirements.

  CloudWatch Log Groups created by Express Mode are configured to never expire and are retained when the Express Mode service is deleted. You can adjust this setting in the CloudWatch Log Group.
+ **Create dashboards and alerts** - Set up CloudWatch; dashboards and alarms for proactive monitoring.

### Deployment strategies

+ **Implement bake times** - Express Mode implements a canary bake time to ensure deployments have time to stabilize while reducing blast radius of problematic deployments. If your application needs more time to stabilize, this can be configured in the Amazon ECS Service definition of your Express Mode service. Refer to [Creating an Amazon ECS canary deployment](AmazonECS/latest/developerguide/deploy-canary-service.html) for more details.
+ **Implement rollback procedures** - Have a plan to quickly revert to previous versions if issues occur.

  Meaningful health checks and alarm based rollbacks can both help with rollback. Express Mode's canary deployment strategy combined with alarm based rollbacks on 4xx and 5xx traffic sets up your deployments for fast rollbacks in the event of faulty application code or configuration.

# Troubleshooting Amazon ECS Express Mode services
Troubleshooting

This section helps you identify and resolve common issues when deploying and managing Express Mode services.

## Deployment issues


### Service stuck in ACTIVE or DRAINING status


**Symptoms:** DescribeServiceRevisions shows resources are still provisioning or deprovisioning. DescribeServices shows deployment not stabilized

**Possible causes and solutions:**
+ **Insufficient IAM permissions** - Verify that the task execution role and infrastructure role have the necessary permissions as shown in their respective managed policies.

  ```
  # Check if the role has the required managed policy
  aws iam list-attached-role-policies --role-name ecsTaskExecutionRole
  ```
+ **Image pull failures** - Ensure the container image exists and is accessible.

  ```
  # Test image pull manually
  docker pull 123456789012.dkr.ecr.us-west-2.amazonaws.com/my-app:latest
  ```
+ **Network connectivity issues** - Check that subnets have internet access or Amazon VPC endpoints for AWS services.
+ **Resource limits** - Verify that your account has sufficient Fargate capacity and hasn't reached service quotas.

**Diagnostic steps:**

1. Use DescribeExpressGatewayService to get your current Service Revisionfollowed by DescribeServiceRevisions for the ServiceRevision to get status on the provisioning or deprovisioning

1. Check the service events in the Amazon ECS console for detailed error messages.

1. Check the container port was set correctly

1. Check AWS service quotas for Amazon ECS and Fargate.

### Task startup failures


**Symptoms:** Tasks fail to start or immediately stop after starting.

**Common causes:**
+ **Application errors** - The container application exits due to configuration or runtime errors.
+ **Health check failures** - The application doesn't respond to health checks on the expected port or path.
+ **Resource constraints** - Insufficient CPU or memory allocation for the application.
+ **Missing environment variables or secrets** - Required configuration is not available to the application.

**Resolution steps:**

1. Check application logs in CloudWatch Logs, obtain the log group name from DescribeServiceRevisions:

   ```
   aws logs describe-log-streams --log-group-name /ecs/express-service-my-app
   aws logs get-log-events --log-group-name /ecs/express-service-my-app --log-stream-name stream-name
   ```

1. Verify that the health check path returns HTTP 200 status.

1. Test the container image locally to ensure it starts correctly.

1. Review and adjust CPU and memory allocations if needed.

## Connectivity issues


### Application unreachable via load balancer


**Symptoms:** The application URL returns timeouts or connection errors.

**Troubleshooting steps:**

1. Validate your resources have finished provisioning

1. Verify that tasks are running and healthy:

   ```
   aws ecs describe-services --cluster my-cluster --services my-express-service
   ```

1. Check Application Load Balancer target group health:

   ```
   aws elbv2 describe-target-health --target-group-arn arn:aws:elasticloadbalancing:region:account:targetgroup/name/id
   ```

1. Ensure the application is listening on the correct port inside the container.

## Performance issues


### Slow response times


**Symptoms:** Application responses are slower than expected.

**Diagnostic approach:**

1. Monitor CPU and memory utilization:

   ```
   # Check CloudWatch metrics for the service
   aws cloudwatch get-metric-statistics \
       --namespace AWS/ECS \
       --metric-name CPUUtilization \
       --dimensions Name=ServiceName,Value=my-express-service Name=ClusterName,Value=my-cluster \
       --start-time 2024-01-01T00:00:00Z \
       --end-time 2024-01-01T01:00:00Z \
       --period 300 \
       --statistics Average
   ```

1. Review application logs for errors or performance warnings.

1. Check if auto scaling is responding appropriately to load.

1. Analyze load balancer metrics for request distribution.

**Optimization strategies:**
+ Increase CPU or memory allocation if resources are constrained.
+ Adjust auto scaling thresholds to scale out earlier.
+ Optimize application code and database queries.

### Auto scaling not working as expected


**Symptoms:** The service doesn't scale up during high load or doesn't scale down during low load.

**Troubleshooting steps:**

1. Check auto scaling policies and their configuration:

   ```
   aws application-autoscaling describe-scaling-policies \
       --service-namespace ecs \
       --resource-id service/my-cluster/my-express-service
   ```

1. Review CloudWatch metrics to ensure scaling triggers are being met.

1. Verify that the service has permission to scale (check IAM roles).

1. Check for any scaling activities and their outcomes.

## Monitoring and debugging tools


### Using CloudWatch Container Insights


Enable Container Insights for comprehensive monitoring:

```
aws ecs put-account-setting --name containerInsights --value enabled
```

Container Insights provides:
+ CPU, memory, disk, and network metrics
+ Performance monitoring dashboards
+ Log correlation and analysis
+ Anomaly detection

# Updating Resources Outside of Express Mode
Updating Resources Outside of Express Mode

Express Mode simplifies deployment by automatically provisioning and managing AWS resources on your behalf, but it's important to understand the responsibility model. While Express Mode creates and configures resources like Amazon ECS services, load balancers, and auto scaling policies, all resources remain in your AWS account and are fully accessible for direct management. You can modify these resources outside of Express Mode using the AWS Console, AWS CLI, or APIs, but doing so may affect Express Mode's ability to manage your service. This section explains which resources Express Mode manages, how to safely make changes outside of Express Mode, and what happens when you do.

## Understanding the shared responsibility model


The responsibility boundary in Express Mode is defined by API usage. Express Mode APIs manage resources on your behalf with coordinated updates across multiple AWS services. Standard AWS service APIs give you direct control over individual resources. This allows you to go beyond the set of parameters that Express Mode provides for configuration, and gives you control over every parameter of every resource. Both sets of APIs operate on the same underlying infrastructure in your account, and both will execute the operations you request. AWS has the responsibility of performing the operation you request. Express Mode does not validate whether resource modifications using direct APIs will conflict with Express Mode configuration, nor does it prevent changes that might disrupt service functionality. This also means that you have the ability to make changes, and those changes will persist. Express Mode will not overwrite changes unless requested as part of an Express Mode update. You're responsible for understanding how modifications using direct APIs interact with Express Mode's configuration and for resolving any resulting conflicts or service issues.

For more details on the defaults that Express Mode sets and the resources that it orchestrates, see [Resources created by Amazon ECS Express Mode services](AmazonECS/latest/developerguide/express-service-work.html).

## Do I need to do anything before I can take advantage of Amazon ECS features in my Express Mode service?


No, there is no graduation path or break glass for Express Mode. The entire Amazon ECS feature set is always available for your Express Mode service. If you'd like to make sure no further Express Mode updates can occur on your service, there are several options. By removing the Managed Tag on your resources, Amazon ECS will no longer be able to identify and operate on it as an Express Mode service. Alternatively, you can also use IAM to restrict user permissions to the Express Mode APIs.

## Example Updates Outside of Express Mode


### Adding a sidecar to an Express Mode service


You can add any sidecar container to your service. This example shows how to add a Fluent Bit logging sidecar.

1. Open the console at [https://console.aws.amazon.com/ecs/v2](https://console.aws.amazon.com/ecs/v2).

1. In the navigation pane, choose **Clusters**.

1. Select the cluster where your Express Mode service is located, and in the **Services** panel, select it.

1. Go to the **Resources** tab and select the task definition.

1. Select the **JSON** tab, and then select the down arrow in the top button labeled **Create New Revision**. Here you'll find an action called **Create New Revision with JSON**.

1. Add the sidecar container before or after your primary container definition. For more information, see [Example Amazon ECS task definition: Route logs to FireLens](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/firelens-taskdef.html).

1. If you have a logging sidecar, like in this example, you'll want to change the `logDriver` in the primary container:

   ```
   "logConfiguration": {
       "logDriver": "awsfirelens"
   }
   ```

1. Assuming the default settings for an Express Mode service, set the primary container memoryReservation to 1998 and the Fluent Bit container memoryReservation to 50. This ensures the total memory reservation across the two containers does not exceed the amount you have running on your Fargate task (2048 for a default Express Mode service). 

1. Create your new revision.

1. Click the drop down that says **Deploy** and select **Update Service**.

1. Select the **Cluster** and **Service** that you're updating, and then select **Force new deployment**. The task definition revision you just created should be auto-selected. Select **Update**.

1. Watch your deployment take place. Tasks in this service will now have two containers. Additional updates through the Express Mode Console or APIs will not overwrite the changes to the task definition, unless they are in direct conflict - for example in this case, if you gave Express Mode a new Log Group and Log Stream name, the logDriver would be updated back to `awslogs`. 

### Adding a custom domain to your service


**Prerequisites:** This guide assumes your domain is a hosted zone managed by Route 53 with an ACM certificate. If your domain is hosted elsewhere, you will need a CNAME to point to the Application Load Balancer DNS record.

1. Open the console at [https://console.aws.amazon.com/ecs/v2](https://console.aws.amazon.com/ecs/v2).

1. In the navigation pane, choose **Clusters**.

1. Select the cluster where your Express Mode service is located, and in the **Services** panel, select it.

1. Go to the **Resources** tab and select the listener rule.

1. Select **Action** and **Edit Rule**.

1. Copy the current Host header value (your Application URL), then **Remove** the rule since there can only be one of each type.

1. Add a condition of type **Host header**, paste your Application URL back in as the Host header condition value.

1. Click **Add OR condition value**.

1. Enter your custom domain here.

1. Click **Next** and **Save Changes**.

1. Now select the **Certificates** tab of the Application Load Balancer listener.

1. Click **Add certificate**. Here you can import the certificate to the listener.

1. In your Route 53 hosted zone, click **Create record** to create a routing record to your service.

1. Select a simple routing record.

1. Add a record name.

1. Select a record type.

1. Route traffic to an **Alias to Application and Classic Load Balancer**.

1. Select your Region.

1. Select the load balancer your Express Mode service uses.

After a few minutes for propagation, your service will begin to receive traffic on the custom domain. If you are adding many certificates to your Application Load Balancer or servicing many Express Mode services from your Application Load Balancer, you may want to consider raising the service limit for certificates on the Application Load Balancer.