• 沒有找到結果。

Amazon ECS

N/A
N/A
Protected

Academic year: 2022

Share "Amazon ECS"

Copied!
456
0
0

加載中.... (立即查看全文)

全文

(1)

Amazon ECS

User Guide for AWS Fargate

(2)

Amazon ECS: User Guide for AWS Fargate

Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon.

(3)

Table of Contents

What is AWS Fargate? ... 1

Components ... 1

Clusters ... 1

Task definitions ... 1

Tasks ... 1

Services ... 1

Operating System and CPU architecture ... 2

Regions ... 2

Windows containers on AWS Fargate considerations ... 2

Getting started walkthroughs ... 3

Pricing ... 3

Getting started ... 4

Setting up ... 4

Sign up for AWS ... 4

Create an IAM user ... 4

Create a virtual private cloud ... 6

Install the AWS CLI ... 6

Docker basics ... 7

Install Docker ... 7

Create a Docker image ... 8

Push your image to Amazon Elastic Container Registry ... 10

Clean up ... 11

Using AWS Copilot ... 11

Prerequisites ... 11

Deploy your application using one command ... 11

Deploy your application step by step ... 12

Using the AWS CDK ... 15

Step 1: Set up your AWS CDK project ... 16

Step 2: Use the AWS CDK to define a containerized Web server on Fargate ... 18

Step 3: Test the Web server ... 21

Step 4: Clean up ... 21

Next steps ... 22

Getting started using the classic console ... 22

Using the classic console with Linux containers on AWS Fargate ... 22

Using the classic console with Windows containers on AWS Fargate ... 25

Developer tools overview ... 30

AWS Management Console ... 30

AWS Command Line Interface ... 30

AWS CloudFormation ... 31

AWS Copilot CLI ... 31

AWS CDK ... 31

AWS App2Container ... 32

Amazon ECS CLI ... 32

Docker Desktop integration with Amazon ECS ... 32

AWS SDKs ... 33

Summary ... 33

Using the AWS Copilot CLI ... 33

Installing the AWS Copilot CLI ... 34

Next steps ... 39

Using the Amazon ECS CLI ... 39

Installing the Amazon ECS CLI ... 40

Configuring the Amazon ECS CLI ... 45

Migrating Configuration Files ... 46

Tutorial: Creating a cluster with a Fargate task using the Amazon ECS CLI ... 47

(4)

Tutorial: Creating an Amazon ECS Service That Uses Service Discovery Using the Amazon ECS

CLI ... 52

Platform versions ... 56

Linux platform versions ... 56

Platform version considerations ... 56

1.4.0 ... 56

1.3.0 ... 57

1.2.0 ... 58

1.1.0 ... 58

1.0.0 ... 59

Migrating to platform version 1.4.0 ... 59

Platform version deprecation ... 59

Windows platform versions ... 60

Platform version considerations ... 60

1.0.0 ... 60

Clusters ... 61

Cluster concepts ... 61

Creating a cluster for the Fargate launch type using the new console ... 62

Setting the cluster default capacity provider using the new console ... 63

Creating a cluster using the classic console ... 63

Capacity providers ... 64

Capacity provider concepts ... 64

Capacity provider types ... 65

Capacity provider considerations ... 65

AWS Fargate capacity providers ... 66

Updating cluster settings ... 70

Deleting a cluster using the new console ... 70

Deleting a cluster using the classic console ... 71

Stopping tasks using the new console ... 71

Task definitions ... 72

Fargate task definition considerations ... 72

Network mode ... 73

Task CPU and memory ... 74

Logging ... 74

Amazon ECS Task execution IAM role ... 74

Example task definition ... 74

Task storage ... 75

Application architecture ... 77

Using the Fargate launch type ... 77

Creating a task definition using the new console ... 78

Creating a task definition using the classic console ... 81

Task definition template ... 83

Task definition parameters ... 87

Family ... 87

Launch types ... 87

Task execution role ... 88

Network mode ... 88

Runtime platform ... 88

Task size ... 89

Container definitions ... 91

Proxy configuration ... 109

Volumes ... 111

Tags ... 112

Other task definition parameters ... 113

Launch types ... 114

Fargate launch type ... 114

Working with 64-bit ARM workloads on Amazon ECS ... 115

(5)

Considerations ... 116

Specifying the ARM architecture in your task definition ... 116

Interfaces for Configuring ARM ... 117

Using data volumes in tasks ... 117

Fargate task storage ... 118

Fargate Linux container platform versions ... 118

Fargate Windows container platform versions ... 118

Amazon EFS volumes ... 119

Bind mounts ... 121

Fargate task networking ... 126

Fargate task networking considerations ... 127

Using a VPC in dual-stack mode ... 128

Using the awslogs log driver ... 128

Turning on the awslogs log driver for your containers ... 128

Creating a log group ... 128

Available awslogs log driver options ... 129

Specifying a log configuration in your task definition ... 131

Viewing awslogs container logs in CloudWatch Logs ... 132

Custom log routing ... 134

Considerations ... 134

Required IAM permissions ... 135

Fluentd buffer limit ... 136

Using Fluent logger libraries or Log4j over TCP ... 137

Using the AWS for Fluent Bit image ... 137

Creating a task definition that uses a FireLens configuration ... 139

Filtering logs using regular expressions ... 142

Example task definitions ... 142

Private registry authentication for tasks ... 147

Required IAM permissions for private registry authentication ... 147

Enabling private registry authentication ... 148

Specifying sensitive data ... 149

Using Secrets Manager ... 149

Using Systems Manager Parameter Store ... 155

Specifying environment variables ... 159

Considerations for specifying environment variable files ... 160

Required IAM permissions ... 161

Example task definitions ... 162

Example: Webserver ... 162

Example: splunk log driver ... 164

Example: fluentd log driver ... 164

Example: gelf log driver ... 165

Example: Container dependency ... 165

Windows sample task definitions ... 166

Updating a task definition using the new console ... 167

Updating a task definition using the classic console ... 168

Deregistering a task definition revision ... 168

Account settings ... 170

Amazon Resource Names (ARNs) and IDs ... 171

ARN and resource ID format timeline ... 172

Viewing account settings ... 172

Modifying account settings ... 173

Scheduling tasks ... 175

Run a standalone task ... 176

Scheduled tasks ... 179

Create a scheduled task ... 180

View your scheduled tasks ... 182

Edit a scheduled task ... 182

(6)

Task maintenance ... 182

Understanding the task retirement notice ... 183

Services ... 185

Service scheduler concepts ... 185

Replica ... 186

Additional service concepts ... 186

Service definition parameters ... 186

Launch type ... 186

Capacity provider strategy ... 187

Task definition ... 188

Platform operating system ... 188

Platform version ... 188

Cluster ... 189

Service name ... 189

Scheduling strategy ... 189

Desired count ... 190

Deployment configuration ... 190

Deployment controller ... 191

Task placement ... 192

Tags ... 193

Network configuration ... 194

Client token ... 197

Service definition template ... 197

Creating a service ... 198

Creating a service using the New Amazon ECS console ... 199

Creating a service using the Classic Amazon ECS console ... 200

Updating a service ... 211

Updating a service using the new console ... 212

Updating a service using the classic console ... 213

Deleting a service ... 214

Deployment types ... 215

Rolling update ... 215

Blue/Green deployment with CodeDeploy ... 218

External deployment ... 222

Service load balancing ... 227

Service load balancing considerations ... 228

Load balancer types ... 229

Creating a load balancer ... 231

Registering multiple target groups with a service ... 237

Service auto scaling ... 239

Service auto scaling and deployments ... 240

IAM permissions required for service auto scaling ... 240

Target tracking scaling policies ... 241

Step scaling policies ... 246

Service Discovery ... 247

Service Discovery concepts ... 248

Service discovery considerations ... 249

Amazon ECS console experience ... 250

Service discovery pricing ... 250

Service throttle logic ... 250

Resources and tags ... 252

Tagging your resources ... 252

Tag basics ... 252

Tagging your resources ... 253

Tag restrictions ... 254

Tagging your resources for billing ... 254

Working with tags using the console ... 255

(7)

Working with tags using the CLI or API ... 256

Service quotas ... 257

Amazon ECS service quotas ... 257

AWS Fargate service quotas ... 259

Managing your Amazon ECS and AWS Fargate service quotas in the AWS Management Console . 260 AWS Fargate Regions ... 261

Supported Regions for Linux containers on AWS Fargate ... 261

Supported Regions for Windows containers on AWS Fargate ... 262

Usage Reports ... 263

Monitoring ... 265

Monitoring tools ... 265

Automated Tools ... 265

Manual Tools ... 266

CloudWatch metrics ... 266

Enabling CloudWatch metrics ... 267

Available metrics and dimensions ... 267

Service utilization ... 269

Service RUNNING task count ... 270

Viewing Amazon ECS metrics ... 270

Usage metrics ... 271

Creating a CloudWatch alarm to monitor Fargate resource usage metrics ... 272

Events and EventBridge ... 273

Amazon ECS events ... 273

Handling events ... 282

CloudWatch Container Insights ... 283

Container Insights considerations ... 283

Setting up CloudWatch Container Insights for cluster and service level metrics ... 284

Collecting application trace data ... 285

Required IAM permissions for AWS Distro for OpenTelemetry integration with AWS X-Ray ... 285

Specifying the AWS Distro for OpenTelemetry sidecar for AWS X-Ray integration in your task definition ... 286

Collecting application metrics ... 287

Exporting application metrics to Amazon CloudWatch ... 287

Exporting application metrics to Amazon Managed Service for Prometheus ... 290

Logging Amazon ECS API calls with AWS CloudTrail ... 292

Amazon ECS information in CloudTrail ... 293

Understanding Amazon ECS log file entries ... 293

Security ... 295

Identity and Access Management ... 295

Audience ... 296

Authenticating with identities ... 296

Managing access using policies ... 298

How Amazon Elastic Container Service works with IAM ... 300

Identity-based policy examples ... 306

AWS managed policies for Amazon ECS ... 315

Service-linked role ... 323

Task execution IAM role ... 329

ECS Anywhere IAM role ... 333

IAM Roles for Tasks ... 335

CodeDeploy IAM Role ... 339

CloudWatch Events IAM Role ... 342

Additional configuration for Windows IAM roles for tasks ... 345

Troubleshooting ... 346

Logging and Monitoring ... 348

Compliance Validation ... 349

Infrastructure Security ... 350

Interface VPC endpoints (AWS PrivateLink) ... 350

(8)

Task metadata endpoint ... 353

Task metadata endpoint v4 ... 353

Enabling the task metadata endpoint ... 353

Task metadata endpoint version 4 paths ... 353

Task metadata JSON response ... 354

Examples ... 356

Task metadata endpoint v3 ... 362

Enabling Task Metadata ... 362

Task Metadata Endpoint Paths ... 362

Task Metadata JSON Response ... 362

Example Task Metadata Response ... 365

Working with other services ... 367

Using Amazon ECR with Amazon ECS ... 367

Using Amazon ECR Images with Amazon ECS ... 367

Creating Amazon ECS resources with AWS CloudFormation ... 368

Amazon ECS and AWS CloudFormation templates ... 368

Learn more about AWS CloudFormation ... 368

Use App Mesh with Amazon ECS ... 368

Tutorials ... 370

Tutorial: Creating a VPC ... 370

Step 1: Create an Elastic IP Address for Your NAT Gateway ... 370

Step 2: Run the VPC Wizard ... 370

Step 3: Create Additional Subnets ... 371

Next Steps ... 372

Tutorial: Creating a cluster with a Fargate Linux task using the AWS CLI ... 372

Prerequisites ... 372

Step 1: Create a Cluster ... 373

Step 2: Register a Linux Task Definition ... 373

Step 3: List Task Definitions ... 374

Step 4: Create a Service ... 375

Step 5: List Services ... 375

Step 6: Describe the Running Service ... 375

Step 7: Test ... 377

Step 8: Clean Up ... 378

Tutorial: Creating a cluster with a Fargate Windows task using the AWS CLI ... 378

Prerequisites ... 378

Step 1: Create a Cluster ... 379

Step 2: Register a Windows Task Definition ... 379

Step 3: List task definitions ... 380

Step 4: Create a service ... 381

Step 5: List services ... 381

Step 6: Describe the Running Service ... 381

Step 7: Clean Up ... 383

Tutorial: Specifying sensitive data using Secrets Manager secrets ... 383

Prerequisites ... 384

Step 1: Create an Secrets Manager secret ... 384

Step 2: Update your task execution IAM role ... 384

Step 3: Create an Amazon ECS task definition ... 385

Step 4: Create an Amazon ECS cluster ... 386

Step 5: Run an Amazon ECS task ... 387

Step 6: Verify ... 387

Step 7: Clean up ... 388

Tutorial: Creating a service using Service Discovery ... 388

Prerequisites ... 389

Step 1: Create the Service Discovery resources ... 389

Step 2: Create the Amazon ECS resources ... 390

Step 3: Verify Service Discovery ... 393

(9)

Step 4: Clean up ... 396

Tutorial: Creating a service using a blue/green deployment ... 397

Prerequisites ... 397

Step 1: Create an Application Load Balancer ... 398

Step 2: Create an Amazon ECS cluster ... 399

Step 3: Register a task definition ... 399

Step 4: Create an Amazon ECS service ... 400

Step 5: Create the AWS CodeDeploy resources ... 401

Step 6: Create and monitor a CodeDeploy deployment ... 402

Step 7: Clean up ... 405

Tutorial: Listening for Amazon ECS CloudWatch Events ... 406

Prerequisite: Set up a test cluster ... 406

Step 1: Create the Lambda function ... 406

Step 2: Register an event rule ... 407

Step 3: Test your rule ... 407

Tutorial: Sending Amazon Simple Notification Service alerts for task stopped events ... 408

Prerequisite: Set up a test cluster ... 408

Step 1: Create and subscribe to an Amazon SNS topic ... 408

Step 2: Register an event rule ... 408

Step 3: Test your rule ... 409

Troubleshooting ... 411

Using Amazon ECS Exec for debugging ... 411

Architecture ... 411

Considerations for using ECS Exec ... 412

Prerequisites for using ECS Exec ... 412

Enabling and using ECS Exec ... 413

Logging and Auditing using ECS Exec ... 415

Using IAM policies to limit access to ECS Exec ... 417

Troubleshooting issues with ECS Exec ... 419

Checking stopped tasks for errors ... 420

Stopped tasks error codes ... 422

CannotPullContainer task errors ... 425

Service event messages ... 427

Service event messages ... 429

Invalid CPU or memory value specified ... 430

Troubleshooting service load balancers ... 431

Troubleshooting service auto scaling ... 432

AWS Fargate throttling limits ... 433

API failure reasons ... 433

Document history ... 435

AWS glossary ... 447

(10)

Components

What is AWS Fargate?

AWS Fargate is a technology that you can use with Amazon ECS to run containers without having to manage servers or clusters of Amazon EC2 instances. With Fargate, you no longer have to provision, configure, or scale clusters of virtual machines to run containers. This removes the need to choose server types, decide when to scale your clusters, or optimize cluster packing.

When you run your Amazon ECS tasks and services with the Fargate launch type or a Fargate capacity provider, you package your application in containers, specify the Operating System, CPU and memory requirements, define networking and IAM policies, and launch the application. Each Fargate task has its own isolation boundary and does not share the underlying kernel, CPU resources, memory resources, or elastic network interface with another task.

For information about Fargate architecture, see Using the Fargate launch type in the Amazon Elastic Container Service Developer Guide

This topic describes the different components of Fargate tasks and services, and calls out special considerations for using Fargate with Amazon ECS.

Components

Clusters

An Amazon ECS cluster is a logical grouping of tasks or services. You can use clusters to isolate your applications. When your tasks are run on Fargate, your cluster resources are also managed by Fargate.

Task definitions

A task definition is a text file that describes one or more containers that form your application. It's in JSON format. You can use it to describe up to a maximum of ten containers. The task definition functions as a blueprint for your application. It specifies the various parameters for your application. For example, you can use it to specify parameters for the operating system, which containers to use, which ports to open for your application, and what data volumes to use with the containers in the task. The specific parameters available for your task definition depend on the needs of your specific application.

Your entire application stack doesn't need to be on a single task definition. In fact, we recommend spanning your application across multiple task definitions. You can do this by combining related containers into their own task definitions, each representing a single component.

Tasks

A task is the instantiation of a task definition within a cluster. After you create a task definition for your application within Amazon ECS, you can specify the number of tasks to run on your cluster. You can run a standalone task, or you can run a task as part of a service.

Services

You can use an Amazon ECS service to run and maintain your desired number of tasks simultaneously in an Amazon ECS cluster. How it works is that, if any of your tasks fail or stop for any reason, the Amazon

(11)

Operating System and CPU architecture

ECS service scheduler launches another instance based on your task definition. It does this to replace it and thereby maintain your desired number of tasks in the service.

Operating System and CPU architecture

The following operating systems are supported:

• Amazon Linux 2

• Windows Server 2019 Full

• Windows Server 2019 Core

If you use Windows containers on Fargate, review the section called “Windows containers on AWS Fargate considerations” (p. 2).

There are 2 architectures available for the Amazon ECS task definition, ARM and X86_64.

When you run Windows containers on Fargate, you must have an X86_64 CPU architecture.

When you run Linux containers on Fargate, you can use the X86_64 CPU architecture, or the ARM64 architecture for your ARM-based applications. For more information, see the section called “Working with 64-bit ARM workloads on Amazon ECS” (p. 115).

Regions

For information about the Regions that support Linux containers on Fargate, see the section called

“Supported Regions for Linux containers on AWS Fargate” (p. 261).

For information about the Regions that support Windows containers on Fargate, see the section called

“Supported Regions for Windows containers on AWS Fargate” (p. 262).

Windows containers on AWS Fargate considerations

Windows containers on AWS Fargate supports the following operating systems:

• Windows Server 2019 Full

• Windows Server 2019 Core

AWS handles the operating system license management, so you do not need any additional Microsoft licenses.

Windows containers on AWS Fargate supports the awslogs driver. For more information, see the section called “Using the awslogs log driver” (p. 128).

Your tasks can run either Linux containers or Windows containers. If you need run both container types, you must create separate tasks.

The following features are not supported on Windows containers on Fargate:

• Group managed service accounts (gMSA)

(12)

Getting started walkthroughs

• Amazon FSx

• ENI trunking

• App Mesh service and proxy integration for tasks

• Firelens log router integration for tasks

• ECS Exec

• Configurable ephemeral storage

• EFS volumes

• The Fargate Spot capacity provider

• Image volumes

The Dockerfile volume option is ignored. Instead, use bind mounts in your task definition. For more information, see Bind mounts (p. 121).

Getting started walkthroughs

The following walkthroughs help you get started using Amazon ECS on Fargate.

• Getting started with the classic console using Linux containers on AWS Fargate (p. 22)

• the section called “Using the classic console with Windows containers on AWS Fargate” (p. 25)

• Tutorial: Creating a cluster with a Fargate Linux task using the AWS CLI (p. 372)

• the section called “Using the classic console with Windows containers on AWS Fargate” (p. 25)

• the section called “Tutorial: Creating a cluster with a Fargate Windows task using the AWS CLI” (p. 378)

For more information about Amazon Elastic Container Service, see What is Amazon ECS?.

Pricing

With Amazon ECS on AWS Fargate, you pay for the vCPU and memory resources your tasks use. For more information, see Fargate Pricing.

Fargate also offers Savings Plans which provides significant savings on your AWS usage. For more information, see the Savings Plans User Guide.

To see your bill, go to the Billing and Cost Management Dashboard in the AWS Billing and Cost Management console. Your bill contains links to usage reports that provide details about your bill. To learn more about AWS account billing, see AWS Account Billing.

If you have questions concerning AWS billing, accounts, and events, contact AWS Support.

For an overview of Trusted Advisor, a service that helps you optimize the costs, security, and performance of your AWS environment, see AWS Trusted Advisor.

(13)

Setting up

Getting started with Amazon ECS

The following guides provide an introduction to the tools available to access Amazon ECS and introductory step by step procedures to run containers. Docker basics takes you through the basic steps to create a Docker container image and upload it to an Amazon ECR private repository. The getting started guides walk you through using the AWS Copilot command line interface and the AWS Management Console to complete the common tasks to run your containers on Amazon ECS and AWS Fargate.

Contents

• Setting up with Amazon ECS (p. 4)

• Docker basics for Amazon ECS (p. 7)

• Getting started with Amazon ECS using AWS Copilot (p. 11)

• Getting started with Amazon ECS using the AWS CDK (p. 15)

• Getting started with Amazon ECS using the classic console (p. 22)

Setting up with Amazon ECS

If you've already signed up for Amazon Web Services (AWS) and have been using Amazon Elastic

Compute Cloud (Amazon EC2), you are close to being able to use Amazon ECS. The set-up process for the two services is similar. The following guide prepares you for launching your first Amazon ECS cluster.

Complete the following tasks to get set up for Amazon ECS.

Sign up for AWS

When you sign up for AWS, your AWS account is automatically signed up for all services, including Amazon EC2 and Amazon ECS. You are charged only for the services that you use.

If you have an AWS account already, skip to the next task. If you don't have an AWS account, use the following procedure to create one.

To create an AWS account

1. Open https://portal.aws.amazon.com/billing/signup.

2. Follow the online instructions.

Part of the sign-up procedure involves receiving a phone call and entering a verification code on the phone keypad.

Note your AWS account number, because you'll need it for the next task.

Create an IAM user

Services in AWS, such as Amazon EC2 and Amazon ECS, require that you provide credentials when you access them, so that the service can determine whether you have permission to access its resources. The console requires your password. You can create access keys for your AWS account to access the command line interface or API. However, we don't recommend that you access AWS using the credentials for your

(14)

Create an IAM user

AWS account; we recommend that you use AWS Identity and Access Management (IAM) instead. Create an IAM user, and then add the user to an IAM group with administrative permissions or and grant this user administrative permissions. You can then access AWS using a special URL and the credentials for the IAM user.

If you signed up for AWS but have not created an IAM user for yourself, you can create one using the IAM console.

To create an administrator user for yourself and add the user to an administrators group (console)

1. Sign in to the IAM console as the account owner by choosing Root user and entering your AWS account email address. On the next page, enter your password.

NoteWe strongly recommend that you adhere to the best practice of using the Administrator IAM user that follows and securely lock away the root user credentials. Sign in as the root user only to perform a few account and service management tasks.

2. In the navigation pane, choose Users and then choose Add user.

3. For User name, enter Administrator.

4. Select the check box next to AWS Management Console access. Then select Custom password, and then enter your new password in the text box.

5. (Optional) By default, AWS requires the new user to create a new password when first signing in. You can clear the check box next to User must create a new password at next sign-in to allow the new user to reset their password after they sign in.

6. Choose Next: Permissions.

7. Under Set permissions, choose Add user to group.

8. Choose Create group.

9. In the Create group dialog box, for Group name enter Administrators.

10. Choose Filter policies, and then select AWS managed - job function to filter the table contents.

11. In the policy list, select the check box for AdministratorAccess. Then choose Create group.

NoteYou must activate IAM user and role access to Billing before you can use the

AdministratorAccess permissions to access the AWS Billing and Cost Management console. To do this, follow the instructions in step 1 of the tutorial about delegating access to the billing console.

12. Back in the list of groups, select the check box for your new group. Choose Refresh if necessary to see the group in the list.

13. Choose Next: Tags.

14. (Optional) Add metadata to the user by attaching tags as key-value pairs. For more information about using tags in IAM, see Tagging IAM entities in the IAM User Guide.

15. Choose Next: Review to see the list of group memberships to be added to the new user. When you are ready to proceed, choose Create user.

You can use this same process to create more groups and users and to give your users access to your AWS account resources. To learn about using policies that restrict user permissions to specific AWS resources, see Access management and Example policies.

To sign in as this new IAM user, sign out of the AWS console, then use the following URL, where your_aws_account_id is your AWS account number without the hyphens (for example, if your AWS account number is 1234-5678-9012, your AWS account ID is 123456789012):

https://your_aws_account_id.signin.aws.amazon.com/console/

(15)

Create a virtual private cloud

Enter the IAM user name and password that you just created. When you're signed in, the navigation bar displays "your_user_name @ your_aws_account_id".

If you don't want the URL for your sign-in page to contain your AWS account ID, you can create an account alias. From the top of the IAM dashboard, to the right of your sign-in link, choose Customize and enter an alias, such as your company name. To sign in after you create an account alias, use the following URL:

https://your_account_alias.signin.aws.amazon.com/console/

To verify the sign-in link for IAM users for your account, open the IAM console and check under IAM users sign-in link on the dashboard.

For more information about IAM, see the AWS Identity and Access Management User Guide.

Create a virtual private cloud

Amazon Virtual Private Cloud (Amazon VPC) enables you to launch AWS resources into a virtual network that you've defined.

NoteThe Amazon ECS console first-run experience creates a VPC for your cluster, so if you intend to use the Amazon ECS console, you can skip to the next section.

If you have a default VPC, you also can skip this section and move to the next task, Install the AWS CLI (p. 6). To determine whether you have a default VPC, see Supported Platforms in the Amazon EC2 Console in the Amazon EC2 User Guide for Linux Instances. Otherwise, you can create a nondefault VPC in your account using the steps below.

Important

If your account supports Amazon EC2 Classic in a region, then you do not have a default VPC in that region.

To create a nondefault VPC

1. Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.

2. From the navigation bar, select a region for the VPC. VPCs are specific to a region, so you should select the same region in which you created your key pair.

3. On the VPC dashboard, choose Launch VPC Wizard.

4. On the Step 1: Select a VPC Configuration page, ensure that VPC with a Single Public Subnet is selected, and choose Select.

5. On the Step 2: VPC with a Single Public Subnet page, enter a friendly name for your VPC in the VPC name field. Leave the other default configuration settings, and choose Create VPC. On the confirmation page, choose OK.

For more information about Amazon VPC, see What is Amazon VPC? in the Amazon VPC User Guide.

Install the AWS CLI

The AWS Management Console can be used to manage all operations manually with Amazon ECS.

However, installing the AWS CLI on your local desktop or a developer box enables you to build scripts that can automate common management tasks in Amazon ECS.

To use the AWS CLI with Amazon ECS, install the latest AWS CLI, version. For information about installing the AWS CLI or upgrading it to the latest version, see Installing the AWS Command Line Interface in the AWS Command Line Interface User Guide.

(16)

Docker basics

Docker basics for Amazon ECS

Docker is a technology that provides the tools for you to build, run, test, and deploy distributed applications that are based on Linux containers. Amazon ECS uses Docker images in task definitions to launch containers as part of tasks in your clusters.

AWS and Docker have collaborated to make a simplified developer experience that enables you to deploy and manage containers on Amazon ECS directly using Docker tools. You can now build and test your containers locally using Docker Desktop and Docker Compose, and then deploy them to Amazon ECS on Fargate. To get started with the Amazon ECS and Docker integration, download Docker Desktop and optionally sign up for a Docker ID. For more information, see Docker Desktop and Docker ID signup.

Docker provides a walkthrough on deploying containers on Amazon ECS. For more information, see Deploying Docker containers on Amazon ECS.

The documentation in this guide assumes that readers possess a basic understanding of what Docker is and how it works. For more information about Docker, see What is Docker? and the Docker overview.

Install Docker

Important

If you already have Docker installed, skip to Create a Docker image (p. 8).

Docker Desktop is an easy-to-install application for your Mac or Windows environment that enables you to build and share containerized applications and microservices. Docker Desktop includes Docker Engine, the Docker CLI client, Docker Compose, and other tools that are helpful when using Docker with Amazon ECS. For more information about how to install Docker Desktop on your preferred operating system, see Docker Desktop overview.

If you don't need a local development environment and you prefer to use an Amazon EC2 instance to use Docker, we provide the following steps to launch an Amazon EC2 instance and install Docker Engine and the Docker CLI.

To install Docker on an Amazon EC2 instance

1. Launch an instance with the Amazon Linux 2 or Amazon Linux AMI. For more information, see Launching an instance in the Amazon EC2 User Guide for Linux Instances.

2. Connect to your instance. For more information, see Connect to your Linux instance in the Amazon EC2 User Guide for Linux Instances.

3. Update the installed packages and package cache on your instance.

sudo yum update -y

4. Install the most recent Docker Engine package.

Amazon Linux 2

sudo amazon-linux-extras install docker

Amazon Linux.

sudo yum install docker 5. Start the Docker service.

sudo service docker start

(17)

Create a Docker image

(Optional) On Amazon Linux 2, to ensure that the Docker daemon starts after each system reboot, run the following command:

sudo systemctl enable docker

6. Add the ec2-user to the docker group so you can execute Docker commands without using sudo.

sudo usermod -a -G docker ec2-user

7. Log out and log back in again to pick up the new docker group permissions. You can accomplish this by closing your current SSH terminal window and reconnecting to your instance in a new one.

Your new SSH session will have the appropriate docker group permissions.

8. Verify that the ec2-user can run Docker commands without sudo.

docker info

Note

In some cases, you may need to reboot your instance to provide permissions for the ec2- user to access the Docker daemon. Try rebooting your instance if you see the following error:

Cannot connect to the Docker daemon. Is the docker daemon running on this host?

Create a Docker image

Amazon ECS task definitions use Docker images to launch containers on the container instances in your clusters. In this section, you create a Docker image of a simple web application, and test it on your local system or Amazon EC2 instance, and then push the image to a container registry (such as Amazon ECR or Docker Hub) so you can use it in an Amazon ECS task definition.

To create a Docker image of a simple web application

1. Create a file called Dockerfile. A Dockerfile is a manifest that describes the base image to use for your Docker image and what you want installed and running on it. For more information about Dockerfiles, go to the Dockerfile Reference.

touch Dockerfile

2. Edit the Dockerfile you just created and add the following content.

FROM ubuntu:18.04

# Install dependencies RUN apt-get update && \ apt-get -y install apache2

# Install apache and write hello world message RUN echo 'Hello World!' > /var/www/html/index.html

# Configure apache

RUN echo '. /etc/apache2/envvars' > /root/run_apache.sh && \ echo 'mkdir -p /var/run/apache2' >> /root/run_apache.sh && \ echo 'mkdir -p /var/lock/apache2' >> /root/run_apache.sh && \ echo '/usr/sbin/apache2 -D FOREGROUND' >> /root/run_apache.sh && \ chmod 755 /root/run_apache.sh

(18)

Create a Docker image

EXPOSE 80

CMD /root/run_apache.sh

This Dockerfile uses the Ubuntu 18.04 image. The RUN instructions update the package caches, install some software packages for the web server, and then write the "Hello World!" content to the web server's document root. The EXPOSE instruction exposes port 80 on the container, and the CMD instruction starts the web server.

3. Build the Docker image from your Dockerfile.

NoteSome versions of Docker may require the full path to your Dockerfile in the following command, instead of the relative path shown below.

docker build -t hello-world .

4. Run docker images to verify that the image was created correctly.

docker images --filter reference=hello-world

Output:

REPOSITORY TAG IMAGE ID CREATED SIZE hello-world latest e9ffedc8c286 4 minutes ago 241MB 5. Run the newly built image. The -p 80:80 option maps the exposed port 80 on the container to

port 80 on the host system. For more information about docker run, go to the Docker run reference.

docker run -t -i -p 80:80 hello-world

NoteOutput from the Apache web server is displayed in the terminal window. You can ignore the "Could not reliably determine the server's fully qualified domain name" message.

6. Open a browser and point to the server that is running Docker and hosting your container.

• If you are using an EC2 instance, this is the Public DNS value for the server, which is the same address you use to connect to the instance with SSH. Make sure that the security group for your instance allows inbound traffic on port 80.

• If you are running Docker locally, point your browser to http://localhost/.

• If you are using docker-machine on a Windows or Mac computer, find the IP address of the VirtualBox VM that is hosting Docker with the docker-machine ip command, substituting machine-name with the name of the docker machine you are using.

docker-machine ip machine-name

You should see a web page with your "Hello World!" statement.

7. Stop the Docker container by typing Ctrl + c.

(19)

Push your image to Amazon Elastic Container Registry

Push your image to Amazon Elastic Container Registry

Amazon ECR is a managed AWS Docker registry service. You can use the Docker CLI to push, pull, and manage images in your Amazon ECR repositories. For Amazon ECR product details, featured customer case studies, and FAQs, see the Amazon Elastic Container Registry product detail pages.

This section requires the following:

• You have the AWS CLI installed and configured. If you do not have the AWS CLI installed on your system, see Installing the AWS Command Line Interface in the AWS Command Line Interface User Guide.

• Your user has the required IAM permissions to access the Amazon ECR service. For more information, see Amazon ECR managed policies.

To tag your image and push it to Amazon ECR

1. Create an Amazon ECR repository to store your hello-world image. Note the repositoryUri in the output.

aws ecr create-repository --repository-name hello-repository --region region

Output:

{ "repository": {

"registryId": "aws_account_id", "repositoryName": "hello-repository",

"repositoryArn": "arn:aws:ecr:region:aws_account_id:repository/hello- repository",

"createdAt": 1505337806.0,

"repositoryUri": "aws_account_id.dkr.ecr.region.amazonaws.com/hello-repository"

} }

2. Tag the hello-world image with the repositoryUri value from the previous step.

docker tag hello-world aws_account_id.dkr.ecr.region.amazonaws.com/hello-repository 3. Run the aws ecr get-login-password command. Specify the registry URI you want to authenticate

to. For more information, see Registry Authentication in the Amazon Elastic Container Registry User Guide.

aws ecr get-login-password | docker login --username AWS --password- stdin aws_account_id.dkr.ecr.region.amazonaws.com

Output:

Login Succeeded

Important

If you receive an error, install or upgrade to the latest version of the AWS CLI. For more information, see Installing the AWS Command Line Interface in the AWS Command Line Interface User Guide.

(20)

Clean up

4. Push the image to Amazon ECR with the repositoryUri value from the earlier step.

docker push aws_account_id.dkr.ecr.region.amazonaws.com/hello-repository

Clean up

When you are done experimenting with your Amazon ECR image, you can delete the repository so you are not charged for image storage.

aws ecr delete-repository --repository-name hello-repository --region region --force

Getting started with Amazon ECS using AWS Copilot

Get started with Amazon ECS using AWS Copilot by deploying an Amazon ECS application.

Prerequisites

Before you begin, make sure that you meet the following prerequisites:

• Set up an AWS account. For more information see Setting up with Amazon ECS (p. 4).

• Install the AWS Copilot CLI. Releases currently support Linux and macOS systems. For more information, see Installing the AWS Copilot CLI (p. 34).

• Install and configure the AWS CLI. For more information, see AWS Command Line Interface.

• Run aws configure to set up a default profile that the AWS Copilot CLI will use to manage your application and services.

• Install and run Docker. For more information, see Get started with Docker.

Deploy your application using one command

Make sure that you have the AWS command line tool installed and have already run aws configure before you start.

Deploy the application using the following command.

git clone https://github.com/aws-samples/amazon-ecs-cli-sample-app.git demo-app && \ cd demo-app && \

copilot init --app demo \ --name api \ --type 'Load Balanced Web Service' \ --dockerfile './Dockerfile' \ --port 80 \ --deploy

(21)

Deploy your application step by step

Deploy your application step by step

Step 1: Configure your credentials

Run aws configure to set up a default profile that the AWS Copilot CLI uses to manage your application and services.

aws configure

Step 2: Clone the demo app

Clone a simple Flask application and Dockerfile.

git clone https://github.com/aws-samples/amazon-ecs-cli-sample-app.git demo-app

Step 3: Set up your application

1. From within the demo-app directory, run the init command.

copilot init

AWS Copilot walks you through the setup of your first application and service with a series of terminal prompts, starting with next step. If you have already used AWS Copilot to deploy applications, you're prompted to choose one from a list of application names.

2. Name your application.

What would you like to name your application? [? for help]

Enter demo.

Step 4: Set up an ECS Service in your "demo" Application

1. You're prompted to choose a service type. You're building a simple Flask application that serves a small API.

Which service type best represents your service's architecture? [Use arrows to move, type to filter, ? for more help]

> Load Balanced Web Service Backend Service

Scheduled Job

Choose Load Balanced Web Service . 2. Provide a name for your service.

What do you want to name this Load Balanced Web Service? [? for help]

Enter api for your service name.

3. Select a Dockerfile.

Which Dockerfile would you like to use for api? [Use arrows to move, type to filter, ? for more help]

(22)

Deploy your application step by step

> ./Dockerfile

Use an existing image instead

Choose Dockerfile. 4. Define port.

Which port do you want customer traffic sent to? [? for help] (80)

Enter 80 or accept default.

5. You will see a log showing the application resources being created.

Creating the infrastructure to manage services under application demo.

6. After the application resources are created, deploy a test environment.

Would you like to deploy a test environment? [? for help] (y/N)

Enter y.

Proposing infrastructure changes for the test environment.

7. You will see a log displaying the status of your application deployment.

Note: It's best to run this command in the root of your Git repository.

Welcome to the Copilot CLI! We're going to walk you through some questions

to help you get set up with an application on ECS. An application is a collection of containerized services that operate together.

Use existing application: No Application name: demo

Workload type: Load Balanced Web Service Service name: api

Dockerfile: ./Dockerfile

no EXPOSE statements in Dockerfile ./Dockerfile Port: 80

Ok great, we'll set up a Load Balanced Web Service named api in application demo listening on port 80.

# Created the infrastructure to manage services under application demo.

# Wrote the manifest for service api at copilot/api/manifest.yml

Your manifest contains configurations like your container size and port (:80).

# Created ECR repositories for service api.

All right, you're all set for local development.

Deploy: Yes

# Created the infrastructure for the test environment.

- Virtual private cloud on 2 availability zones to hold your services [Complete]

- Virtual private cloud on 2 availability zones to hold your services [Complete]

- Internet gateway to connect the network to the internet [Complete]

- Public subnets for internet facing services [Complete]

- Private subnets for services that can't be reached from the internet [Complete]

- Routing tables for services to talk with each other [Complete]

- ECS Cluster to hold your services [Complete]

# Linked account aws_account_id and region region to application demo.

(23)

Deploy your application step by step

# Created environment test in region region under application demo.

Environment test is already on the latest version v1.0.0, skip upgrade.

[+] Building 0.8s (7/7) FINISHED

=> [internal] load .dockerignore 0.1s

=> => transferring context: 2B 0.0s

=> [internal] load build definition from Dockerfile 0.0s

=> => transferring dockerfile: 37B 0.0s

=> [internal] load metadata for docker.io/library/nginx:latest 0.7s

=> [internal] load build context 0.0s

=> => transferring context: 32B 0.0s

=> [1/2] FROM docker.io/library/

nginx@sha256:aeade65e99e5d5e7ce162833636f692354c227ff438556e5f3ed0335b7cc2f1b 0.0s => CACHED [2/2] COPY index.html /usr/share/nginx/html 0.0s

=> exporting to image 0.0s

=> => exporting layers 0.0s

=> => writing image

sha256:3ee02fd4c0f67d7bd808ed7fc73263880649834cbb05d5ca62380f539f4884c4 0.0s

=> => naming to aws_account_id.dkr.ecr.region.amazonaws.com/demo/api:cee7709 0.0s

WARNING! Your password will be stored unencrypted in /home/user/.docker/config.json.

Configure a credential helper to remove this warning. See

https://docs.docker.com/engine/reference/commandline/login/#credentials-store Login Succeeded

The push refers to repository [aws_account_id.dkr.ecr.region.amazonaws.com/demo/api]

592a5c0c47f1: Pushed 6c7de695ede3: Pushed 2f4accd375d9: Pushed ffc9b21953f4: Pushed cee7709: digest: sha_digest

# Deployed api, you can access it at http://demo- Publi-1OQ8VMS2VC2WG-561733989.region.elb.amazonaws.com.

Step 5: Verify your application is running

View the status of your application by using the following commands.

List all of your AWS Copilot applications.

copilot app ls

Show information about the environments and services in your application.

copilot app show

Show information about your environments.

(24)

Using the AWS CDK

copilot env ls

Show information about the service, including endpoints, capacity and related resources.

copilot svc show

List of all the services in an application.

copilot svc ls

Show logs of a deployed service.

copilot svc logs

Show service status.

copilot svc status

List available commands and options.

copilot --help

copilot init --help

Step 6. Learn to create a CI/CD Pipeline

Instructions can be found in the ECS Workshop detailing how to fully automate a CI/CD pipeline and git workflow using AWS Copilot.

Step 7: Clean up

Run the following command to delete and clean up all resources.

copilot app delete

Getting started with Amazon ECS using the AWS CDK

This topic shows you how to deploy a containerized Web server with Amazon Elastic Container Service and the AWS Cloud Development Kit (CDK) on Fargate. The AWS CDK is an Infrastructure as Code (IAC) framework that lets you define AWS infrastructure using a full-fledged programming language. You write an app in one of the CDK's supported languages, containing one or more stacks, then synthesize it to an AWS CloudFormation template and deploy the resources to your AWS account.

The AWS Construct Library, included with the CDK, provides APIs that model the resources provided by every AWS service. For the most popular services, the library provides curated constructs that provide

(25)

Step 1: Set up your AWS CDK project

smart defaults and implement best practices with fewer required parameters. One of these modules, aws-ecs-patterns, provides high-level abstractions that let you define your containerized service and all necessary supporting resources in only a few lines of code.

The construct we'll be using in this topic is ApplicationLoadBalancedFargateService. As you can likely tell from the name, this construct deploys an Amazon ECS service on Fargate behind an application load balancer. The aws-ecs-patterns module also includes constructs that use a network load balancer and/or run on Amazon EC2, if you'd prefer those options.

Before embarking on this task, set up your AWS CDK development environment as described in Getting Started With the AWS CDK - Prerequisites, then install the AWS CDK by issuing:

npm install -g aws-cdk

Note

These instructions assume you are using AWS CDK v2.

Topics

• Step 1: Set up your AWS CDK project (p. 16)

• Step 2: Use the AWS CDK to define a containerized Web server on Fargate (p. 18)

• Step 3: Test the Web server (p. 21)

• Step 4: Clean up (p. 21)

• Next steps (p. 22)

Step 1: Set up your AWS CDK project

Create a directory for your new AWS CDK app and initialize the project.

TypeScript

mkdir hello-ecs cd hello-ecs

cdk init --language typescript

JavaScript

mkdir hello-ecs cd hello-ecs

cdk init --language javascript

Python

mkdir hello-ecs cd hello-ecs

cdk init --language python

After the project has been initialized, activate the project's virtual environment and install the AWS CDK's baseline dependencies.

source .venv/bin/activate

python -m pip install -r requirements.txt

(26)

Step 1: Set up your AWS CDK project

Java

mkdir hello-ecs cd hello-ecs

cdk init --language java

Import this Maven project to your Java IDE (for example, in Eclipse, use File > Import > Maven >

Existing Maven Projects).

C#

mkdir hello-ecs cd hello-ecs

cdk init --language csharp

Note

Be sure to name the directory hello-ecs as shown. The AWS CDK application template uses the name of the project directory to generate names for source files and classes. If you use a different name, your app will not match these instructions.

AWS CDK v2 includes stable constructs for all AWS services in a single package, dubbed aws-cdk-lib.

This package is installed as a dependency when you initialize the project (or, in some languages, the first time you build it). In this topic, we use an Amazon ECS Patterns construct, which provides high-level abstractions for working with Amazon ECS. In turn, this module relies on Amazon ECS constructs and others to provision the reseources needed by your Amazon ECS application.

The names you use to import these libraries into your CDK application differs slightly depending on which programming language you use. For reference, here are the names used in each supported CDK programming language.

TypeScript

@aws-cdk-lib/aws-ecs

@aws-cdk-lib/aws-ecs-patterns

JavaScript

@aws-cdk-/aws-ecs

@aws-cdk-lib/aws-ecs-patterns

Python

aws_cdk.aws_ecs

aws_cdk.aws_ecs_patterns

Java

software.amazon.awscdk.services.ecs

software.amazon.awscdk.services.ecs.patterns

C#

Amazon.CDK.AWS.ECS

Amazon.CDK.AWS.ECS.Patterns

(27)

Step 2: Use the AWS CDK to define a containerized Web server on Fargate

Step 2: Use the AWS CDK to define a containerized Web server on Fargate

We'll use the container image amazon-ecs-sample from DockerHub. This image contains a PHP Web app running under Amazon Linux 2.

In the AWS CDK project you created, edit the file containing the definition of the stack to look like the code below. You'll recognize the instantiation of the ApplicationLoadBalancedFargateService construct—or at least its name.

NoteWhat's a stack? The stack is the unit of deployment: all resources must be in a stack, and all the resources in a stack are deployed together. If a resource fails to deploy, any other resources already deployed are rolled back. An AWS CDK app can contain multiple stacks, and resources in one stack can refer to resources in in another.

TypeScript

Update lib/hello-ecs-stack.ts to read as follows.

import * as cdk from '@aws-cdk-lib';

import { Construct } from 'constructs';

import * as ecs from '@aws-cdk-lib/aws-ecs';

import * as ecsp from '@aws-cdk-lib/aws-ecs-patterns';

export class HelloEcsStack extends cdk.Stack {

constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props);

new ecsp.ApplicationLoadBalancedFargateService(this, 'MyWebServer', { taskImageOptions: {

image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), },

publicLoadBalancer: true });

}}

JavaScript

Update lib/hello-ecs-stack.js to read as follows.

const cdk = require('@aws-cdk-lib');

const { Construct } = require('constructs');

const ecs = require('@aws-cdk-lib/aws-ecs');

const ecsp = require('@aws-cdk-lib/aws-ecs-patterns');

class HelloEcsStack extends cdk.Stack {

constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props);

new ecsp.ApplicationLoadBalancedFargateService(this, 'MyWebServer', { taskImageOptions: {

image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), },

publicLoadBalancer: true });

}

(28)

Step 2: Use the AWS CDK to define a containerized Web server on Fargate }

module.exports = { HelloEcsStack }

Python

Update hello-ecs/hello_ecs_stack.py to read as follows.

import aws_cdk as cdk

from constructs import Construct import aws_cdk.aws_ecs as ecs

import aws_cdk.aws_ecs_patterns as ecsp class HelloEcsStack(cdk.Stack):

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:

super().__init__(scope, construct_id, **kwargs)

ecsp.ApplicationLoadBalancedFargateService(self, "MyWebServer", task_image_options=ecsp.ApplicationLoadBalancedTaskImageOptions(

image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")), public_load_balancer=True

)

Java

Update src/main/java/com.myorg/HelloEcsStack.java to read as follows.

package com.myorg;

import software.constructs.Construct;

import software.amazon.awscdk.Stack;

import software.amazon.awscdk.StackProps;

import software.amazon.awscdk.services.ecs.ContainerImage;

import

software.amazon.awscdk.services.ecs.patterns.ApplicationLoadBalancedFargateService;

import

software.amazon.awscdk.services.ecs.patterns.ApplicationLoadBalancedTaskImageOptions;

public class HelloEcsStack extends Stack {

public HelloEcsStack(final Construct scope, final String id) { this(scope, id, null);

}

public HelloEcsStack(final Construct scope, final String id, final StackProps props) {

super(scope, id, props);

ApplicationLoadBalancedFargateService.Builder.create(this, "MyWebServer") .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder() .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample")) .build())

.publicLoadBalancer(true) .build();

} }

C#

Update src/HelloEcs/HelloEcsStack.cs to read as follows.

(29)

Step 2: Use the AWS CDK to define a containerized Web server on Fargate

using Amazon.CDK;

using Constructs;

using Amazon.CDK.AWS.ECS;

using Amazon.CDK.AWS.ECS.Patterns;

namespace HelloEcs

{ public class HelloEcsStack : Stack {

internal HelloEcsStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)

{

new ApplicationLoadBalancedFargateService(this, "MyWebServer", new ApplicationLoadBalancedFargateServiceProps

{

TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {

Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample") },

PublicLoadBalancer = true });

} } }

You can see in this short snippet:

• The service's logical name, MyWebServer.

• The container image, obtained from DockerHub, amazon/amazon-ecs-sample..

• The fact that the load balancer will have a public address and will thus be accessible from the Internet.

If you omit, as we have done here, the Amazon ECS cluster, the underlying Amazon Virtual Private Cloud and Amazon EC2 instances, an Auto Scaling Group, the Application Load Balancer, the necessary IAM roles and policies, and other AWS resources required to deploy the Web server, the AWS CDK will also create these resources. Some automatically-provisioned resources will be shared by all Amazon ECS services defined in the stack.

Save the source file, then issue cdk synth in the app's main directory. The AWS CDK runs the app and synthesizes an AWS CloudFormation template from it, then displays the template. The template is about 600 lines of YAML, so only the beginning is shown here. (Your template may have differences from ours.)

Resources:

MyWebServerLB3B5FD3AB:

Type: AWS::ElasticLoadBalancingV2::LoadBalancer Properties:

LoadBalancerAttributes:

- Key: deletion_protection.enabled Value: "false"

Scheme: internet-facing SecurityGroups:

- Fn::GetAtt:

- MyWebServerLBSecurityGroup01B285AA - GroupId

Subnets:

- Ref: EcsDefaultClusterMnL3mNNYNVpcPublicSubnet1Subnet3C273B99 - Ref: EcsDefaultClusterMnL3mNNYNVpcPublicSubnet2Subnet95FF715A Type: application

DependsOn:

(30)

Step 3: Test the Web server

- EcsDefaultClusterMnL3mNNYNVpcPublicSubnet1DefaultRouteFF4E2178 - EcsDefaultClusterMnL3mNNYNVpcPublicSubnet2DefaultRouteB1375520 Metadata:

aws:cdk:path: HelloEcsStack/MyWebServer/LB/Resource MyWebServerLBSecurityGroup01B285AA:

Type: AWS::EC2::SecurityGroup Properties:

GroupDescription: Automatically created Security Group for ELB HelloEcsStackMyWebServerLB06757F57

SecurityGroupIngress:

- CidrIp: 0.0.0.0/0

Description: Allow from anyone on port 80 FromPort: 80

IpProtocol: tcp ToPort: 80 VpcId:

Ref: EcsDefaultClusterMnL3mNNYNVpc7788A521 Metadata:

aws:cdk:path: HelloEcsStack/MyWebServer/LB/SecurityGroup/Resource

# and so on for another few hundred lines

To actually deploy the service in your AWS account, issue cdk deploy. You'll be asked to approve the IAM policies the AWS CDK has generated.

Deployment will take several minutes. You'll see the AWS CDK create quite a number of resources. The last few lines of the output from the deployment include the public hostname of the load balancer and an HTTP URL for your new Web server.

Outputs:

HelloEcsStack.MyWebServerLoadBalancerDNSXXXXXXX = Hello-MyWeb-ZZZZZZZZZZZZZ-ZZZZZZZZZZ.us- west-2.elb.amazonaws.com

HelloEcsStack.MyWebServerServiceURLYYYYYYYY = http://Hello-MyWeb-ZZZZZZZZZZZZZ- ZZZZZZZZZZ.us-west-2.elb.amazonaws.com

Step 3: Test the Web server

Copy the URL from the deployment output and paste it into your Web browser. You should see a welcome message from the Web server.

Step 4: Clean up

Now that you're done with the Web server (it doesn't do anything besides display the Congratulations message), you can tear down the service using the CDK. Issue cdk destroy in your app's main directory.

Doing this will prevent unintended AWS charges.

(31)

Next steps

Next steps

To learn more about developing AWS infrastructure using the AWS CDK, see the AWS CDK Developer Guide.

For information about writing AWS CDK apps in your language of choice, see:

TypeScript

Working with the AWS CDK in TypeScript JavaScript

Working with the AWS CDK in JavaScript Python

Working with the AWS CDK in Python Java

Working with the AWS CDK in Java C#

Working with the AWS CDK in C#

For more information on the AWS Construct Library modules used in this topic, see the AWS CDK API Reference overviews below.

• aws-ecs

• aws-ecs-patterns

Getting started with Amazon ECS using the classic console

The following guides provide an introduction to the classic AWS Management Console to complete the common tasks to run your containers on Amazon ECS and AWS Fargate.

Contents

• Getting started with the classic console using Linux containers on AWS Fargate (p. 22)

• Getting started with the classic Amazon ECS console using Windows containers on AWS Fargate (p. 25)

Getting started with the classic console using Linux containers on AWS Fargate

Amazon Elastic Container Service (Amazon ECS) is a highly scalable, fast, container management service that makes it easy to run, stop, and manage your containers. You can host your containers on a serverless infrastructure that is managed by Amazon ECS by launching your services or tasks on AWS Fargate. For a broad overview on Amazon ECS on Fargate, see What is AWS Fargate? (p. 1).

Get started with Amazon ECS on AWS Fargate by using the Fargate launch type for your tasks. In the Regions where Amazon ECS supports AWS Fargate, the classic Amazon ECS first-run wizard guides you

(32)

Using the classic console with Linux containers on AWS Fargate

through the process of getting started with Amazon ECS using the Fargate launch type. The wizard gives you the option of creating a cluster and launching a sample web application. If you already have a Docker image to launch in Amazon ECS, you can create a task definition with that image and use that for your cluster instead.

Complete the following steps to get started with Amazon ECS on AWS Fargate.

Prerequisites

Before you begin, be sure that you've completed the steps in Setting up with Amazon ECS (p. 4) and that your AWS user has either the permissions specified in the AdministratorAccess or Amazon ECS first-run wizard permissions (p. 307) IAM policy example.

The first-run wizard attempts to automatically create the task execution IAM role, which is required for Fargate tasks. To ensure that the first-run experience is able to create this IAM role, one of the following must be true:

• Your user has administrator access. For more information, see Setting up with Amazon ECS (p. 4).

• Your user has the IAM permissions to create a service role. For more information, see Creating a Role to Delegate Permissions to an AWS Service.

• A user with administrator access has manually created the task execution role so that it is available on the account to be used. For more information, see Amazon ECS task execution IAM role (p. 329).

Step 1: Create a task definition

A task definition is like a blueprint for your application. Each time you launch a task in Amazon ECS, you specify a task definition. The service then knows which Docker image to use for containers, how many containers to use in the task, and the resource allocation for each container.

1. Open the classic console first-run wizard at https://console.aws.amazon.com/ecs/home#/firstRun.

2. From the navigation bar, select the US East (N. Virginia) Region.

NoteYou can complete this first-run wizard using these steps for any Region that supports Amazon ECS using Fargate. For more information, see Fargate launch type (p. 114).

3. Configure your container definition parameters.

For Container definition, the first-run wizard comes preloaded with the sample-app, nginx, and tomcat-webserver container definitions in the console. You can optionally rename the container or review and edit the resources used by the container (such as CPU units and memory limits) by choosing Edit and editing the values shown. For more information, see Container definitions (p. 91).

NoteIf you are using an Amazon ECR image in your container definition, be sure to use the full registry/repository:tag naming for your Amazon ECR images. For example, aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app:latest.

4. For Task definition, the first-run wizard defines a task definition to use with the preloaded container definitions. You can optionally rename the task definition and edit the resources used by the task (such as the Task memory and Task CPU values) by choosing Edit and editing the values shown. For more information, see Task definition parameters (p. 87).

Task definitions created in the first-run wizard are limited to a single container for simplicity. You can create multi-container task definitions later in the Amazon ECS console.

5. Choose Next.

(33)

Using the classic console with Linux containers on AWS Fargate

Step 2: Configure the service

In this section of the wizard, select how to configure the Amazon ECS service that is created from your task definition. A service launches and maintains a specified number of copies of the task definition in your cluster. The Amazon ECS sample application is a web-based Hello World–style application that is meant to run indefinitely. By running it as a service, it restarts if the task becomes unhealthy or unexpectedly stops.

The first-run wizard comes preloaded with a service definition, and you can see the sample-app- service service defined in the console. You can optionally rename the service or review and edit the details by choosing Edit and doing the following:

1. In the Service name field, select a name for your service.

2. In the Number of desired tasks field, enter the number of tasks to launch with your specified task definition.

3. In the Security group field, specify a range of IPv4 addresses to allow inbound traffic from, in CIDR block notation. For example, 203.0.113.0/24.

4. (Optional) You can choose to use an Application Load Balancer with your service. When a task is launched from a service that is configured to use a load balancer, the task is registered with the load balancer. Traffic from the load balancer is distributed across the instances in the load balancer. For more information, see Introduction to Application Load Balancers.

Important

Application Load Balancers do incur cost while they exist in your AWS resources. For more information, see Application Load Balancer Pricing.

Complete the following steps to use a load balancer with your service.

• In the Container to load balance section, choose the Load balancer listener port. The default value here is set up for the sample application, but you can configure different listener options for the load balancer. For more information, see Service load balancing (p. 227).

5. Review your service settings and click Save, Next.

Step 3: Configure the cluster

In this section of the wizard, you name your cluster, and then Amazon ECS takes care of the networking and IAM configuration for you.

1. In the Cluster name field, choose a name for your cluster.

2. Click Next to proceed.

Step 4: Review

1. Review your task definition, task configuration, and cluster configuration and click Create to finish.

You are directed to a Launch Status page that shows the status of your launch. It describes each step of the process (this can take a few minutes to complete while your Auto Scaling group is created and populated).

2. After the launch is complete, choose View service.

Step 5: View your service

If your service is a web-based application, such as the Amazon ECS sample application, you can view its containers with a web browser.

參考文獻

相關文件

– The The readLine readLine method is the same method used to read method is the same method used to read  from the keyboard, but in this case it would read from a 

bility of the mobile system is the same as the call blocking For example, for a hexagonal planar layout with reuse dis- probability in a cell, Because traffic in

Once you get down to a purely business level, your influence is gone and the true light of your life isdimmed. You must work in the missionary spirit, with a breadth of charity

• A down-and-in option is a call knock-in option that comes into existence only when the barrier is reached and H < S.. • An up-and-in is a put knock-in option that comes

• A knock-in (KI) option comes into existence if a certain barrier is reached.. • A down-and-in option is a call knock-in option that comes into existence only when the barrier

• A knock-in option comes into existence if a certain barrier is reached.. • A down-and-in option is a call knock-in option that comes into existence only when the barrier is

• A knock-in option comes into existence if a certain barrier is reached?. • A down-and-in option is a call knock-in option that comes into existence only when the barrier is

• A knock-in option comes into existence if a certain barrier is reached.. • A down-and-in option is a call knock-in option that comes into existence only when the barrier is