

# Using the ECS managed Docker platform branch in Elastic Beanstalk
ECS managed platform branch

This topic provides an overview of the Elastic Beanstalk ECS managed Docker platform branches for Amazon Linux 2 and Amazon Linux 2023. It also provides configuration information that's specific to the Docker ECS managed platform. 

**Migration from Multi-container Docker on AL1**  
On [July 18, 2022](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2022-07-18-linux-al1-retire.html), Elastic Beanstalk set the status of all platform branches based on Amazon Linux AMI (AL1) to **retired**. Although this chapter provides configuration information for this retired platform, we strongly recommend that you migrate to the latest supported platform branch. If you're presently using the retired *Multi-container Docker running on AL1* platform branch, you can migrate to the latest *ECS Running on AL2023* platform branch. The latest platform branch supports all of the features from the discontinued platform branch. No changes to the source code are required. For more information, see [Migrating your Elastic Beanstalk application from ECS managed Multi-container Docker on AL1 to ECS on Amazon Linux 2023](migrate-to-ec2-AL2-platform.md).

## ECS managed Docker platform overview


Elastic Beanstalk uses Amazon Elastic Container Service (Amazon ECS) to coordinate container deployments to ECS managed Docker environments. Amazon ECS provides tools to manage a cluster of instances running Docker containers. Elastic Beanstalk takes care of Amazon ECS tasks including cluster creation, task definition and execution. Each of the instances in the environment run the same set of containers, which are defined in a `Dockerrun.aws.json` v2 file. In order to get the most out of Docker, Elastic Beanstalk lets you create an environment where your Amazon EC2 instances run multiple Docker containers side by side.

The following diagram shows an example Elastic Beanstalk environment configured with three Docker containers running on each Amazon EC2 instance in an Auto Scaling group:

![\[Elastic Beanstalk environment with load balancer, auto scaling group, and containerized tasks.\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/aeb-multicontainer-docker-example.png)


## Amazon ECS resources created by Elastic Beanstalk


When you create an environment using the ECS managed Docker platform, Elastic Beanstalk automatically creates and configures several Amazon Elastic Container Service resources while building the environment. In doing so, it creates the necessary containers on each Amazon EC2 instance. 
+ **Amazon ECS Cluster** – Container instances in Amazon ECS are organized into clusters. When used with Elastic Beanstalk, one cluster is always created for each ECS managed Docker environment. An ECS cluster also contains Auto Scaling group capacity providers and other resources.
+ **Amazon ECS Task Definition** – Elastic Beanstalk uses the `Dockerrun.aws.json` v2 in your project to generate the Amazon ECS task definition that is used to configure container instances in the environment. 
+ **Amazon ECS Task** – Elastic Beanstalk communicates with Amazon ECS to run a task on every instance in the environment to coordinate container deployment. In a scalable environment, Elastic Beanstalk initiates a new task whenever an instance is added to the cluster. 
+ **Amazon ECS Container Agent** – The agent runs in a Docker container on the instances in your environment. The agent polls the Amazon ECS service and waits for a task to run. 
+ **Amazon ECS Data Volumes** – In addition to the volumes that you define in the `Dockerrun.aws.json` v2, Elastic Beanstalk inserts volume definitions into the task definition to facilitate log collection. 

  Elastic Beanstalk creates log volumes on the container instance, one for each container, at `/var/log/containers/containername`. These volumes are named `awseb-logs-containername` and are provided for containers to mount. See [Container definition format](create_deploy_docker_v2config.md#create_deploy_docker_v2config_dockerrun_format) for details on how to mount them.

For more information about Amazon ECS resources, see the [Amazon Elastic Container Service Developer Guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html).

## `Dockerrun.aws.json` v2 file


The container instances require a configuration file named `Dockerrun.aws.json`. *Container instances* refers to Amazon EC2 instances running ECS managed Docker in an Elastic Beanstalk environment. This file is specific to Elastic Beanstalk and can be used alone or combined with source code and content in a [source bundle](applications-sourcebundle.md) to create an environment on a Docker platform. 

**Note**  
The Version 2 format of the `Dockerrun.aws.json` adds support for multiple containers per Amazon EC2 instance and can only be used with an ECS managed Docker platform. The format differs significantly from the other configuration file versions that support the Docker platform branches that aren't managed by ECS.

 See the [`Dockerrun.aws.json` v2](create_deploy_docker_v2config.md#create_deploy_docker_v2config_dockerrun) for details on the updated format and an example file. 

## Docker images


 The ECS managed Docker platform for Elastic Beanstalk requires images to be prebuilt and stored in a public or private online image repository before creating an Elastic Beanstalk environment.

**Note**  
Building custom images during deployment with a `Dockerfile` is not supported by the ECS managed Docker platform on Elastic Beanstalk. Build your images and deploy them to an online repository before creating an Elastic Beanstalk environment.

Specify images by name in `Dockerrun.aws.json` v2.

To configure Elastic Beanstalk to authenticate to a private repository, include the `authentication` parameter in your `Dockerrun.aws.json` v2 file. 

## Failed container deployments


 If an Amazon ECS task fails, one or more containers in your Elastic Beanstalk environment will not start. Elastic Beanstalk does not roll back multi-container environments due to a failed Amazon ECS task. If a container fails to start in your environment, redeploy the current version or a previous working version from the Elastic Beanstalk console. 

**To deploy an existing version**

1. Open the Elastic Beanstalk console in your environment's region.

1. Click **Actions** to the right of your application name and then click **View application versions**.

1. Select a version of your application and click **Deploy**.

## Extending ECS based Docker platforms for Elastic Beanstalk
Extending ECS based Docker platforms

Elastic Beanstalk offers extensibility features that enable you to apply your own commands, scripts, software, and configurations to your application deployments. The deployment workflow for the *ECS AL2 and AL2023* platform branches varies slightly from the other Linux based platforms. For more information, see [Instance deployment workflow for ECS running on Amazon Linux 2 and laterInstance deployment workflow for ECS on AL2 and later](platforms-linux-extend.workflow.ecs-al2.md). 

# ECS managed Docker configuration for Elastic Beanstalk


This chapter explains how to configure your ECS managed Docker environment. The following list summarizes the configuration items that this chapter explains.
+  `Dockerrun.aws.json` v2 – This configuration file specifies your image repository and the name of your Docker images, among other components. 
+ EC2 Instance profile role – If you have a custom instance profile, we explain how to configure it so that the permissions required for ECS to manage your containers stay current.
+ Elastic Load Balancing listeners – You'll need to configure multiple Elastic Load Balancing listeners if you need your environment to support inbound traffic for proxies or other services that don't run on the default HTTP port.

**Topics**
+ [

# Configuring the Dockerrun.aws.json v2 file
](create_deploy_docker_v2config.md)
+ [

# Container managed policy and EC2 instance role
](create_deploy_docker_ecs_role.md)
+ [

# Using multiple Elastic Load Balancing listeners
](create_deploy_docker_ecs_listeners.md)

# Configuring the Dockerrun.aws.json v2 file
Dockerrun.aws.json v2 file

`Dockerrun.aws.json v2` is an Elastic Beanstalk configuration file that describes how to deploy a set of Docker containers hosted in an ECS cluster in an Elastic Beanstalk environment. The Elastic Beanstalk platform creates an ECS *task definition*, which includes an ECS *container definition*. These definitions are described in the `Dockerrun.aws.json` configuration file.

The container definition in the `Dockerrun.aws.json` file describes the containers to deploy to each Amazon EC2 instance in the ECS cluster. In this case an Amazon EC2 instance is also referred to as a host *container instance*, because it hosts the Docker containers. The configuration file also describes the data volumes to create on the host container instance for the Docker containers to mount. For more information and a diagram of the components in an ECS managed Docker environment on Elastic Beanstalk, see the [ECS managed Docker platform overview](create_deploy_docker_ecs.md#create_deploy_docker_ecs_platform) earlier in this chapter.

 A `Dockerrun.aws.json` file can be used on its own or zipped up with additional source code in a single archive. Source code that is archived with a `Dockerrun.aws.json` is deployed to Amazon EC2 container instances and accessible in the `/var/app/current/` directory.

**Topics**
+ [

## `Dockerrun.aws.json` v2
](#create_deploy_docker_v2config_dockerrun)
+ [

## Volume format
](#create_deploy_docker_v2config_volume_format)
+ [

## Execution Role ARN format
](#create_deploy_docker_v2config_executionRoleArn_format)
+ [

## Container definition format
](#create_deploy_docker_v2config_dockerrun_format)
+ [

## Authentication format – using images from a private repository
](#docker-multicontainer-dockerrun-privaterepo)
+ [

## Example Dockerrun.aws.json v2
](#create_deploy_docker_v2config_example)

## `Dockerrun.aws.json` v2


The `Dockerrun.aws.json` file includes the following sections:

**AWSEBDockerrunVersion**  
Specifies the version number as the value `2` for ECS managed Docker environments.

**executionRoleArn **  
Specifies the task execution IAM roles for different purposes and services associated with your account. For your application to use Elastic Beanstalk [environment variables stored as secrets](AWSHowTo.secrets.env-vars.md), you’ll need to specify the ARN of a task execution role that grants the required permissions. Other common use cases may also require this parameter. For more information, see [Execution Role ARN format](#create_deploy_docker_v2config_executionRoleArn_format).

**volumes**  
Creates volumes from folders in the Amazon EC2 container instance, or from your source bundle (deployed to `/var/app/current`). Mount these volumes to paths within your Docker containers using `mountPoints` in the `containerDefinitions` section.

**containerDefinitions**  
An array of container definitions.

**authentication (optional)**  
The location in Amazon S3 of a `.dockercfg` file that contains authentication data for a private repository.

The *containerDefinitions* and *volumes * sections of `Dockerrun.aws.json` use the same formatting as the corresponding sections of an Amazon ECS task definition file. For more information about the task definition format and a full list of task definition parameters, see [Amazon ECS task definitions](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_defintions.html) in the *Amazon Elastic Container Service Developer Guide*.

## Volume format


The *volume* parameter creates volumes from either folders in the Amazon EC2 container instance, or from your source bundle (deployed to `/var/app/current`).

 Volumes are specified in the following format: 

```
"volumes": [
    {
      "name": "volumename",
      "host": {
        "sourcePath": "/path/on/host/instance"
      }
    }
  ],
```

Mount these volumes to paths within your Docker containers using `mountPoints` in the container definition.

Elastic Beanstalk configures additional volumes for logs, one for each container. These should be mounted by your Docker containers in order to write logs to the host instance. 

For more details, see the `mountPoints` field in the *Container definition format* section that follows.

## Execution Role ARN format


In order for your application to use Elastic Beanstalk [environment variables stored as secrets](AWSHowTo.secrets.env-vars.md), you'll need to specify a task execution IAM role. The role must grant the Amazon ECS container permission to make AWS API calls on your behalf using AWS Secrets Manager secrets or AWS Systems Manager Parameter Store parameters to reference sensitive data. For instructions to create a task execution IAM role with the required permissions for your account, see [Amazon ECS task execution IAM role ](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html) in the Amazon Elastic Container Service Developer Guide.

```
{
"AWSEBDockerrunVersion": 2,
  "executionRoleArn": "arn:aws:iam::111122223333:role/ecsTaskExecutionRole",
```

### Additional permissions required for the Amazon ECS managed Docker platform
ECS managed Docker

**EC2 instance profile grants `iam:PassRole` to ECS**  
In order for your EC2 instance profile to be able to grant this role to the ECS container, you must include the `iam:PassRole` permission demonstrated in the following example. The `iam:PassRole` allows the EC2 instances permission *to pass * the task execution role to the ECS container.

In this example, we limit the EC2 instance to only pass the role to the ECS service. Although this condition is not required, we add it to follow best practices to reduce the scope of the permission shared. We accomplish this with the `Condition` element.

**Note**  
Any usage of the ECS IAM task execution role requires the `iam:PassRole` permission. There are other common use cases that require the ECS task execution managed service role. For more information, see [Amazon ECS task execution IAM role ](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html) in the Amazon Elastic Container Service Developer Guide.



**Example policy with `iam:PassRole` permission**    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": [
                "arn:aws:iam::123456789012:role/ecs-task-execution-role"
            ],
            "Condition": {
                "StringLike": {
                    "iam:PassedToService": "ecs-tasks.amazonaws.com"
                }
            }
        }
    ]
}
```





**Granting secrets and parameters access to the Amazon ECS container agent**  
The Amazon ECS task execution IAM role also needs permissions to access the secrets and parameter stores. Similar to the requirements of the EC2 instance profile role, the ECS container agent requires permission to pull the necessary Secrets Manager or Systems Manager resources. For more information, see [Secrets Manager or Systems Manager permissions](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html#task-execution-secrets) in the *Amazon Elastic Container Service Developer Guide*

**Granting secrets and parameters access to the Elastic Beanstalk EC2 instances**  
To support secrets configured as environment variables, you'll also need to add permissions to your EC2 instance profile. For more information, see [Fetching secrets and parameters to Elastic Beanstalk environment variables](AWSHowTo.secrets.env-vars.md) and [Required IAM permissions for Secrets Manager](AWSHowTo.secrets.IAM-permissions.md#AWSHowTo.secrets.IAM-permissions.secrets-manager).

The following examples combine the previous `iam:PassRole` example with the examples provided in the referenced [Required IAM permissions for Secrets Manager](AWSHowTo.secrets.IAM-permissions.md#AWSHowTo.secrets.IAM-permissions.secrets-manager). They add the permissions that the EC2 instances require to access the AWS Secrets Manager and AWS Systems Manager stores to retrieve the secrets and parameter data to initialize the Elastic Beanstalk environment variables that have been configured for secrets.

**Example Secrets Manager policy combined with `iam:PassRole` permission**    
****  

```
{
    "Version": "2012-10-17",
    "Statement": [
       {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": [
                "arn:aws:iam::123456789012:role/ecs-task-execution-role"
            ],
            "Condition": {
                "StringLike": {
                    "iam:PassedToService": "ecs-tasks.amazonaws.com"
               }
            } 
        },
        {
            "Effect": "Allow",
            "Action": [
                "secretsmanager:GetSecretValue",
                "kms:Decrypt"          
            ],
            "Resource": [
                "arn:aws:secretsmanager:us-east-1:111122223333:secret:my-secret",
                "arn:aws:kms:us-east-1:111122223333:key/my-key"
            ]
        }
    ]
}
```

**Example Systems Manager policy combined with `iam:PassRole` permission**    
****  

```
{
    "Version": "2012-10-17",
    "Statement": [
       {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": [
                "arn:aws:iam::123456789012:role/ecs-task-execution-role"
            ],
            "Condition": {
                "StringLike": {
                    "iam:PassedToService": "ecs-tasks.amazonaws.com"
               }
            } 
        },
        {
            "Effect": "Allow",
            "Action": [
                "ssm:GetParameter",
                "kms:Decrypt"
            ],
            "Resource": [
                "arn:aws:ssm:us-east-1:111122223333:parameter/my-parameter",
                "arn:aws:kms:us-east-1:111122223333:key/my-key"
            ]
        }
    ]
}
```

## Container definition format


The following examples show a subset of parameters that are commonly used in the *containerDefinitions* section. More optional parameters are available.

The Beanstalk platform creates an ECS *task definition*, which includes an ECS *container definition*. Beanstalk supports a sub-set of parameters for the ECS container definition. For more information, see [Container definitions](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definitions) in the *Amazon Elastic Container Service Developer Guide*.

A `Dockerrun.aws.json` file contains an array of one or more container definition objects with the following fields:

**name**  
The name of the container. See [Standard Container Definition Parameters](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#standard_container_definition_params) for information about the maximum length and allowed characters.

**image**  
The name of a Docker image in an online Docker repository from which you're building a Docker container. Note these conventions:   
+  Images in official repositories on Docker Hub use a single name (for example, `ubuntu` or `mongo`).
+ Images in other repositories on Docker Hub are qualified with an organization name (for example, `amazon/amazon-ecs-agent`.
+ Images in other online repositories are qualified further by a domain name (for example, `quay.io/assemblyline/ubuntu`).

**environment**  
An array of environment variables to pass to the container.  
For example, the following entry defines an environment variable with the name **Container** and the value **PHP**:  

```
"environment": [
  {
    "name": "Container",
    "value": "PHP"
  }
],
```

**essential**  
True if the task should stop if the container fails. Nonessential containers can finish or crash without affecting the rest of the containers on the instance. 

**memory**  
Amount of memory on the container instance to reserve for the container. Specify a non-zero integer for one or both of the `memory` or `memoryReservation` parameters in container definitions.

**memoryReservation**  
The soft limit (in MiB) of memory to reserve for the container. Specify a non-zero integer for one or both of the `memory` or `memoryReservation` parameters in container definitions.

**mountPoints**  
Volumes from the Amazon EC2 container instance to mount, and the location on the Docker container file system at which to mount them. When you mount volumes that contain application content, your container can read the data you upload in your source bundle. When you mount log volumes for writing log data, Elastic Beanstalk can gather log data from these volumes.   
 Elastic Beanstalk creates log volumes on the container instance, one for each Docker container, at `/var/log/containers/containername`. These volumes are named `awseb-logs-containername` and should be mounted to the location within the container file structure where logs are written.   
For example, the following mount point maps the nginx log location in the container to the Elastic Beanstalk–generated volume for the `nginx-proxy` container.   

```
{
  "sourceVolume": "awseb-logs-nginx-proxy",
  "containerPath": "/var/log/nginx"
}
```

**portMappings**  
Maps network ports on the container to ports on the host.

**links**  
List of containers to link to. Linked containers can discover each other and communicate securely. 

**volumesFrom**  
Mount all of the volumes from a different container. For example, to mount volumes from a container named `web`:  

```
"volumesFrom": [
  {
    "sourceContainer": "web"
  }
],
```

## Authentication format – using images from a private repository


The `authentication` section contains authentication data for a private repository. This entry is optional.

Add the information about the Amazon S3 bucket that contains the authentication file in the `authentication` parameter of the `Dockerrun.aws.json` file. Make sure that the `authentication` parameter contains a valid Amazon S3 bucket and key. The Amazon S3 bucket must be hosted in the same region as the environment that is using it. Elastic Beanstalk will not download files from Amazon S3 buckets hosted in other regions.

Uses the following format:

```
"authentication": {
    "bucket": "amzn-s3-demo-bucket",
    "key": "mydockercfg"
  },
```

For information about generating and uploading the authentication file, see [Authenticating with image repositoriesUsing AWS Secrets Manager](docker-configuration.remote-repo.md).

## Example Dockerrun.aws.json v2


The following snippet is an example that illustrates the syntax of the `Dockerrun.aws.json` file for an instance with two containers.

```
{
  "AWSEBDockerrunVersion": 2,
  "volumes": [
    {
      "name": "php-app",
      "host": {
        "sourcePath": "/var/app/current/php-app"
      }
    },
    {
      "name": "nginx-proxy-conf",
      "host": {
        "sourcePath": "/var/app/current/proxy/conf.d"
      }
    }
  ],
  "containerDefinitions": [
    {
      "name": "php-app",
      "image": "php:fpm",
      "environment": [
        {
          "name": "Container",
          "value": "PHP"
        }
      ],
      "essential": true,
      "memory": 128,
      "mountPoints": [
        {
          "sourceVolume": "php-app",
          "containerPath": "/var/www/html",
          "readOnly": true
        }
      ]
    },
    {
      "name": "nginx-proxy",
      "image": "nginx",
      "essential": true,
      "memory": 128,
      "portMappings": [
        {
          "hostPort": 80,
          "containerPort": 80
        }
      ],
      "links": [
        "php-app"
      ],
      "mountPoints": [
        {
          "sourceVolume": "php-app",
          "containerPath": "/var/www/html",
          "readOnly": true
        },
        {
          "sourceVolume": "nginx-proxy-conf",
          "containerPath": "/etc/nginx/conf.d",
          "readOnly": true
        },
        {
          "sourceVolume": "awseb-logs-nginx-proxy",
          "containerPath": "/var/log/nginx"
        }
      ]
    }
  ]
}
```

# Container managed policy and EC2 instance role


When you create an environment in the Elastic Beanstalk console, it prompts you to create a default instance profile that includes the `AWSElasticBeanstalkMulticontainerDocker` managed policy. So initially, your default EC2 instance profile, should include this managed policy. If your environment uses a custom EC2 instance profile role instead of the default, make sure that the managed policy `AWSElasticBeanstalkMulticontainerDocker` is attached so the required permissions for container management stay up-to-date. 

Elastic Beanstalk uses an Amazon ECS-optimized AMI with an Amazon ECS container agent that runs in a Docker container. The agent communicates with Amazon ECS to coordinate container deployments. In order to communicate with Amazon ECS, each Amazon EC2 instance must have the corresponding IAM permissions, which are specified in this managed policy. See the [AWSElasticBeanstalkMulticontainerDocker](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AWSElasticBeanstalkMulticontainerDocker.html) in the *AWS Managed Policy Reference Guide* to view these permissions.

If you use Elastic Beanstalk environment variables that are configured to access secrets or parameters that are stored in AWS Secrets Manager or AWS Systems Manager Parameter Store, you must customize your EC2 instance profile with additional permissions. For more information, see [Execution Role ARN format](create_deploy_docker_v2config.md#create_deploy_docker_v2config_executionRoleArn_format). 



# Using multiple Elastic Load Balancing listeners
Multiple Elastic Load Balancing listeners

You can configure multiple Elastic Load Balancing listeners on a ECS managed Docker environment in order to support inbound traffic for proxies or other services that don't run on the default HTTP port.

Create a `.ebextensions` folder in your source bundle and add a file with a `.config` file extension. The following example shows a configuration file that creates an Elastic Load Balancing listener on port 8080.

**`.ebextensions/elb-listener.config`**

```
option_settings:
  aws:elb:listener:8080:
    ListenerProtocol: HTTP
    InstanceProtocol: HTTP
    InstancePort: 8080
```

If your environment is running in a custom [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC) that you created, Elastic Beanstalk takes care of the rest. In a default VPC, you need to configure your instance's security group to allow ingress from the load balancer. Add a second configuration file that adds an ingress rule to the security group:

**`.ebextensions/elb-ingress.config`**

```
Resources:
  port8080SecurityGroupIngress:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 8080
      FromPort: 8080
      SourceSecurityGroupName: { "Fn::GetAtt": ["AWSEBLoadBalancer", "SourceSecurityGroup.GroupName"] }
```

For more information on the configuration file format, see [Adding and customizing Elastic Beanstalk environment resources](environment-resources.md) and [Option settings](ebextensions-optionsettings.md). 

 In addition to adding a listener to the Elastic Load Balancing configuration and opening a port in the security group, you need to map the port on the host instance to a port on the Docker container in the `containerDefinitions` section of the `Dockerrun.aws.json` v2 file. The following excerpt shows an example: 

```
"portMappings": [
  {
    "hostPort": 8080,
    "containerPort": 8080
  }
]
```

See [`Dockerrun.aws.json` v2](create_deploy_docker_v2config.md#create_deploy_docker_v2config_dockerrun) for details about the `Dockerrun.aws.json` v2 file format. 

# Creating an ECS managed Docker environment with the Elastic Beanstalk console
Tutorial - ECS managed Docker

This tutorial details container configuration and source code preparation for an ECS managed Docker environment that uses two containers. 

The containers, a PHP application and an nginx proxy, run side by side on each of the Amazon Elastic Compute Cloud (Amazon EC2) instances in an Elastic Beanstalk environment. After creating the environment and verifying that the applications are running, you'll connect to a container instance to see how it all fits together.

**Topics**
+ [

## Define ECS managed Docker containers
](#create_deploy_docker_ecstutorial_config)
+ [

## Add content
](#create_deploy_docker_ecstutorial_code)
+ [

## Deploy to Elastic Beanstalk
](#create_deploy_docker_ecstutorial_deploy)
+ [

## Connect to a container instance
](#create_deploy_docker_ecstutorial_connect)
+ [

## Inspect the Amazon ECS container agent
](#create_deploy_docker_ecstutorial_connect_inspect)

## Define ECS managed Docker containers


The first step in creating a new Docker environment is to create a directory for your application data. This folder can be located anywhere on your local machine and have any name you choose. In addition to a container configuration file, this folder will contain the content that you will upload to Elastic Beanstalk and deploy to your environment. 

**Note**  
All of the code for this tutorial is available in the awslabs repository on GitHub at [https://github.com/awslabs/eb-docker-nginx-proxy](https://github.com/awslabs/eb-docker-nginx-proxy).

The file that Elastic Beanstalk uses to configure the containers on an Amazon EC2 instance is a JSON-formatted text file named `Dockerrun.aws.json` v2. The ECS managed Docker platform versions use a Version 2 format of this file. This format can only be used with the ECS managed Docker platform, as it differs significantly from the other configuration file versions that support the Docker platform branches that aren't managed by ECS.

Create a `Dockerrun.aws.json` v2 text file with this name at the root of your application and add the following text: 

```
{
  "AWSEBDockerrunVersion": 2,
  "volumes": [
    {
      "name": "php-app",
      "host": {
        "sourcePath": "/var/app/current/php-app"
      }
    },
    {
      "name": "nginx-proxy-conf",
      "host": {
        "sourcePath": "/var/app/current/proxy/conf.d"
      }
    }  
  ],
  "containerDefinitions": [
    {
      "name": "php-app",
      "image": "php:fpm",
      "essential": true,
      "memory": 128,
      "mountPoints": [
        {
          "sourceVolume": "php-app",
          "containerPath": "/var/www/html",
          "readOnly": true
        }
      ]
    },
    {
      "name": "nginx-proxy",
      "image": "nginx",
      "essential": true,
      "memory": 128,
      "portMappings": [
        {
          "hostPort": 80,
          "containerPort": 80
        }
      ],
      "links": [
        "php-app"
      ],
      "mountPoints": [
        {
          "sourceVolume": "php-app",
          "containerPath": "/var/www/html",
          "readOnly": true
        },
        {
          "sourceVolume": "nginx-proxy-conf",
          "containerPath": "/etc/nginx/conf.d",
          "readOnly": true
        },
        {
          "sourceVolume": "awseb-logs-nginx-proxy",
          "containerPath": "/var/log/nginx"
        }
      ]
    }
  ]
}
```

This example configuration defines two containers, a PHP web site with an nginx proxy in front of it. These two containers will run side by side in Docker containers on each instance in your Elastic Beanstalk environment, accessing shared content (the content of the website) from volumes on the host instance, which are also defined in this file. The containers themselves are created from images hosted in official repositories on Docker Hub. The resulting environment looks like the following:

![\[Elastic Beanstalk environment with load balancer, auto scaling group, and two instances running Nginx and PHP-FPM.\]](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/images/aeb-multicontainer-tutorial.png)


The volumes defined in the configuration correspond to the content that you will create next and upload as part of your application source bundle. The containers access content on the host by mounting volumes in the `mountPoints` section of the container definitions. 

For more information on the format of `Dockerrun.aws.json` v2 and its parameters, see [Container definition format](create_deploy_docker_v2config.md#create_deploy_docker_v2config_dockerrun_format). 

## Add content


Next you will add some content for your PHP site to display to visitors, and a configuration file for the nginx proxy. 

**php-app/index.php**

```
<h1>Hello World!!!</h1>
<h3>PHP Version <pre><?= phpversion()?></pre></h3>
```

**php-app/static.html**

```
<h1>Hello World!</h1>
<h3>This is a static HTML page.</h3>
```

**proxy/conf.d/default.conf**

```
server {
  listen 80;
  server_name localhost;
  root /var/www/html;
 
  index index.php;
 
  location ~ [^/]\.php(/|$) {
    fastcgi_split_path_info ^(.+?\.php)(/.*)$;
    if (!-f $document_root$fastcgi_script_name) {
      return 404;
    }

    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;

    fastcgi_pass php-app:9000;
    fastcgi_index index.php;
  }
}
```

## Deploy to Elastic Beanstalk


Your application folder now contains the following files:

```
├── Dockerrun.aws.json
├── php-app
│   ├── index.php
│   └── static.html
└── proxy
    └── conf.d
        └── default.conf
```

This is all you need to create the Elastic Beanstalk environment. Create a `.zip` archive of the above files and folders (not including the top-level project folder). To create the archive in Windows explorer, select the contents of the project folder, right-click, select **Send To**, and then click **Compressed (zipped) Folder** 

**Note**  
For information on the required file structure and instructions for creating archives in other environments, see [Create an Elastic Beanstalk application source bundle](applications-sourcebundle.md) 

Next, upload the source bundle to Elastic Beanstalk and create your environment. For **Platform**, select **Docker**. For **Platform branch**, select **ECS running on 64bit Amazon Linux 2023**.

**To launch an environment (console)**

1. Open the Elastic Beanstalk console with this preconfigured link: [console.aws.amazon.com/elasticbeanstalk/home\$1/newApplication?applicationName=tutorials&environmentType=LoadBalanced](https://console.aws.amazon.com/elasticbeanstalk/home#/newApplication?applicationName=tutorials&environmentType=LoadBalanced)

1. For **Platform**, select the platform and platform branch that match the language used by your application, or the Docker platform for container-based applications.

1. For **Application code**, choose **Upload your code**.

1. Choose **Local file**, choose **Choose file**, and then open the source bundle.

1. Choose **Review and launch**.

1. Review the available settings, and then choose **Create app**.

The Elastic Beanstalk console redirects you to the management dashboard for your new environment. This screen shows the health status of the environment and events output by the Elastic Beanstalk service. When the status is Green, click the URL next to the environment name to see your new website. 

## Connect to a container instance


Next you will connect to an Amazon EC2 instance in your Elastic Beanstalk environment to see some of the moving parts in action. 

The easiest way to connect to an instance in your environment is by using the EB CLI. To use it, [install the EB CLI](eb-cli3.md#eb-cli3-install), if you haven't done so already. You'll also need to configure your environment with an Amazon EC2 SSH key pair. Use either the console's [security configuration page](using-features.managing.security.md) or the EB CLI [eb init](eb3-init.md) command to do that. To connect to an environment instance, use the EB CLI [eb ssh](eb3-ssh.md) command.

Now that your connected to an Amazon EC2 instance hosting your docker containers, you can see how things are set up. Run `ls` on `/var/app/current`: 

```
[ec2-user@ip-10-0-0-117 ~]$ ls /var/app/current
Dockerrun.aws.json  php-app  proxy
```

This directory contains the files from the source bundle that you uploaded to Elastic Beanstalk during environment creation. 

```
[ec2-user@ip-10-0-0-117 ~]$ ls /var/log/containers
nginx-proxy    nginx-proxy-4ba868dbb7f3-stdouterr.log     
php-app        php-app-dcc3b3c8522c-stdouterr.log       rotated
```

This is where logs are created on the container instance and collected by Elastic Beanstalk. Elastic Beanstalk creates a volume in this directory for each container, which you mount to the container location where logs are written. 

You can also take a look at Docker to see the running containers with `docker ps`. 

```
[ec2-user@ip-10-0-0-117 ~]$ sudo docker ps
CONTAINER ID   IMAGE                            COMMAND                  CREATED         STATUS                  PORTS                               NAMES                                                
4ba868dbb7f3   nginx                            "/docker-entrypoint.…"   4 minutes ago   Up 4 minutes            0.0.0.0:80->80/tcp, :::80->80/tcp   ecs-awseb-Tutorials-env-dc2aywfjwg-1-nginx-proxy-acca84ef87c4aca15400        
dcc3b3c8522c   php:fpm                          "docker-php-entrypoi…"   4 minutes ago   Up 4 minutes            9000/tcp                            ecs-awseb-Tutorials-env-dc2aywfjwg-1-php-app-b8d38ae288b7b09e8101                             
d9367c0baad6   amazon/amazon-ecs-agent:latest   "/agent"                 5 minutes ago   Up 5 minutes (healthy)                                      ecs-agent
```

This shows the two running containers that you deployed, as well as the Amazon ECS container agent that coordinated the deployment. 

## Inspect the Amazon ECS container agent


Amazon EC2 instances in a ECS managed Docker environment on Elastic Beanstalk run an agent process in a Docker container. This agent connects to the Amazon ECS service in order to coordinate container deployments. These deployments run as tasks in Amazon ECS, which are configured in task definition files. Elastic Beanstalk creates these task definition files based on the `Dockerrun.aws.json` that you upload in a source bundle. 

Check the status of the container agent with an HTTP get request to `http://localhost:51678/v1/metadata`: 

```
[ec2-user@ip-10-0-0-117 ~]$ curl http://localhost:51678/v1/metadata
{
  "Cluster":"awseb-Tutorials-env-dc2aywfjwg",
  "ContainerInstanceArn":"arn:aws:ecs:us-west-2:123456789012:container-instance/awseb-Tutorials-env-dc2aywfjwg/db7be5215cd74658aacfcb292a6b944f",
  "Version":"Amazon ECS Agent - v1.57.1 (089b7b64)"
}
```

This structure shows the name of the Amazon ECS cluster, and the ARN ([Amazon Resource Name](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html)) of the cluster instance (the Amazon EC2 instance that you are connected to). 

For more information, make an HTTP get request to `http://localhost:51678/v1/tasks`:

```
[ec2-user@ip-10-0-0-117 ~]$ curl http://localhost:51678/v1/tasks
{
   "Tasks":[
      {
         "Arn":"arn:aws:ecs:us-west-2:123456789012:task/awseb-Tutorials-env-dc2aywfjwg/bbde7ebe1d4e4537ab1336340150a6d6",
         "DesiredStatus":"RUNNING",
         "KnownStatus":"RUNNING",
         "Family":"awseb-Tutorials-env-dc2aywfjwg",
         "Version":"1",
         "Containers":[
            {
               "DockerId":"dcc3b3c8522cb9510b7359689163814c0f1453b36b237204a3fd7a0b445d2ea6",
               "DockerName":"ecs-awseb-Tutorials-env-dc2aywfjwg-1-php-app-b8d38ae288b7b09e8101",
               "Name":"php-app",
               "Volumes":[
                  {
                     "Source":"/var/app/current/php-app",
                     "Destination":"/var/www/html"
                  }
               ]
            },
            {
               "DockerId":"4ba868dbb7f3fb3328b8afeb2cb6cf03e3cb1cdd5b109e470f767d50b2c3e303",
               "DockerName":"ecs-awseb-Tutorials-env-dc2aywfjwg-1-nginx-proxy-acca84ef87c4aca15400",
               "Name":"nginx-proxy",
               "Ports":[
                  {
                     "ContainerPort":80,
                     "Protocol":"tcp",
                     "HostPort":80
                  },
                  {
                     "ContainerPort":80,
                     "Protocol":"tcp",
                     "HostPort":80
                  }
               ],
               "Volumes":[
                  {
                     "Source":"/var/app/current/php-app",
                     "Destination":"/var/www/html"
                  },
                  {
                     "Source":"/var/log/containers/nginx-proxy",
                     "Destination":"/var/log/nginx"
                  },
                  {
                     "Source":"/var/app/current/proxy/conf.d",
                     "Destination":"/etc/nginx/conf.d"
                  }
               ]
            }
         ]
      }
   ]
}
```

This structure describes the task that is run to deploy the two docker containers from this tutorial's example project. The following information is displayed: 
+ **KnownStatus** – The `RUNNING` status indicates that the containers are still active.
+ **Family** – The name of the task definition that Elastic Beanstalk created from `Dockerrun.aws.json`.
+ **Version** – The version of the task definition. This is incremented each time the task definition file is updated.
+ **Containers** – Information about the containers running on the instance.

Even more information is available from the Amazon ECS service itself, which you can call using the AWS Command Line Interface. For instructions on using the AWS CLI with Amazon ECS, and information about Amazon ECS in general, see the [ Amazon ECS User Guide](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_GetStarted.html). 

# Migrating your Elastic Beanstalk application from ECS managed Multi-container Docker on AL1 to ECS on Amazon Linux 2023
Migration to ECS running on AL2023

**Note**  
On [July 18, 2022](https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2022-07-18-linux-al1-retire.html), Elastic Beanstalk set the status of all platform branches based on Amazon Linux AMI (AL1) to **retired**..

This topic guides you in the migration of your applications from the retired platform branch *Multi-container Docker running on 64bit Amazon Linux* to *ECS Running on 64bit AL2023*. This target platform branch is current and supported. Like the previous *Multi-container Docker AL1* branch, the newer *ECS AL2023* platform branch uses Amazon ECS to coordinate deployment of multiple Docker containers to an Amazon ECS cluster in an Elastic Beanstalk environment. The new *ECS AL2023* platform branch supports all of the features in the previous *Multi-container Docker AL1* platform branch. Also, the same `Dockerrun.aws.json` v2 file is supported.

**Topics**
+ [

## Migrate with the Elastic Beanstalk console
](#migrate-to-ec2-AL2-platform-steps-console)
+ [

## Migrate with the AWS CLI
](#migrate-to-ec2-AL2-platform-steps-cli)

## Migrate with the Elastic Beanstalk console
Elastic Beanstalk console

To migrate using the Elastic Beanstalk console deploy the same source code to a new environment that’s based on the *ECS Running on AL2023* platform branch. No changes to the source code are required. 

**To migrate to the *ECS Running on Amazon Linux 2023* platform branch**

1. Using the application source that's already deployed to the old environment, create an application source bundle. You can use the same application source bundle and the same `Dockerrun.aws.json` v2 file.

1. Create a new environment using the *ECS Running on Amazon Linux 2023* platform branch. Use the source bundle from the prior step for **Application code**. For more detailed steps, see [Deploy to Elastic Beanstalk](create_deploy_docker_ecstutorial.md#create_deploy_docker_ecstutorial_deploy) in the *ECS managed Docker tutorial* earlier in this chapter.

## Migrate with the AWS CLI
AWS CLI

You also have the option to use the AWS Command Line Interface (AWS CLI) to migrate your existing *Multi-container Docker Amazon Linux Docker* environment to the newer *ECS AL2023* platform branch. In this case you don't need to create a new environment or redeploy your source code. You only need to run the AWS CLI [update-environment](https://docs.aws.amazon.com/cli/latest/reference/elasticbeanstalk/update-environment.html) command. It will perform a platform update to migrate your existing environment to the *ECS Amazon Linux 2023* platform branch.

Use the following syntax to migrate your environment to the new platform branch.

```
aws elasticbeanstalk update-environment \
--environment-name my-env \
--solution-stack-name "64bit Amazon Linux 2023 version running ECS" \
--region my-region
```

The following is an example of the command to migrate environment *beta-101* to *version 3.0.0* of the *ECS Amazon Linux 2023* platform branch in the *us-east-1* region. 

```
aws elasticbeanstalk update-environment \
--environment-name beta-101 \
--solution-stack-name "64bit Amazon Linux 2023 v4.0.0 running ECS" \
--region us-east-1
```

The `solution-stack-name` parameter provides the platform branch and its version. Use the most recent platform branch *version* by specifying the proper *solution stack name*. The version of every platform branch is included in the *solution stack name*, as shown in the above example. For a list of the most current solution stacks for the Docker platform, see [Supported platforms](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.docker) in the *AWS Elastic Beanstalk Platforms* guide.

**Note**  
 The [list-available-solution-stacks](https://docs.aws.amazon.com/cli/latest/reference/elasticbeanstalk/list-available-solution-stacks.html) command provides a list of the platform versions available for your account in an AWS Region.  

```
aws elasticbeanstalk list-available-solution-stacks --region us-east-1 --query SolutionStacks
```

To learn more about the AWS CLI, see the [https://docs.aws.amazon.com//cli/latest/userguide/cli-chap-welcome.html](https://docs.aws.amazon.com//cli/latest/userguide/cli-chap-welcome.html). For more information about AWS CLI commands for Elastic Beanstalk, see the [https://docs.aws.amazon.com//cli/latest/reference/elasticbeanstalk/index.html](https://docs.aws.amazon.com//cli/latest/reference/elasticbeanstalk/index.html).