# @aws-cdk/aws-ecs 中文文档

规范地址：https://npmcn.com/package/%40aws-cdk/aws-ecs/

版本：1\.204\.0
npm 元数据更新时间：2023-11-21T10:15:09.675Z
中文译文更新时间：2026-11-07T11:48:14.698Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40aws-cdk/aws-ecs
原文对照：https://npmcn.com/package/%40aws-cdk/aws-ecs/?lang=original
项目主页：https://github.com/aws/aws-cdk
源码仓库：https://github.com/aws/aws-cdk

弃用说明：AWS CDK v1 has reached End-of-Support on 2023-06-01\. This package is no longer being updated, and users should migrate to AWS CDK v2\. For more information on how to migrate, see https://docs\.aws\.amazon\.com/cdk/v2/guide/migrating-v2\.html

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：5.6 MB，99 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>= 14\.15\.0
- 运行依赖：26 个
- peer 依赖：@aws-cdk/aws-applicationautoscaling 1\.204\.0，@aws-cdk/aws-autoscaling 1\.204\.0，@aws-cdk/aws-autoscaling-hooktargets 1\.204\.0，@aws-cdk/aws-certificatemanager 1\.204\.0，@aws-cdk/aws-cloudwatch 1\.204\.0，@aws-cdk/aws-ec2 1\.204\.0，@aws-cdk/aws-ecr 1\.204\.0，@aws-cdk/aws-ecr-assets 1\.204\.0，@aws-cdk/aws-elasticloadbalancing 1\.204\.0，@aws-cdk/aws-elasticloadbalancingv2 1\.204\.0，@aws-cdk/aws-iam 1\.204\.0，@aws-cdk/aws-kms 1\.204\.0，@aws-cdk/aws-lambda 1\.204\.0，@aws-cdk/aws-logs 1\.204\.0，@aws-cdk/aws-route53 1\.204\.0，@aws-cdk/aws-route53-targets 1\.204\.0，@aws-cdk/aws-s3 1\.204\.0，@aws-cdk/aws-s3-assets 1\.204\.0，@aws-cdk/aws-secretsmanager 1\.204\.0，@aws-cdk/aws-servicediscovery 1\.204\.0，@aws-cdk/aws-sns 1\.204\.0，@aws-cdk/aws-sqs 1\.204\.0，@aws-cdk/aws-ssm 1\.204\.0，@aws-cdk/core 1\.204\.0，@aws-cdk/cx-api 1\.204\.0，constructs ^3\.3\.69
- 首次发布：2018-07-31T13:33:13.173Z
- 最新版本发布：2023-06-19T21:10:50.144Z
- 近 30 天下载量：117748（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：288（近 12 个月 0 个）

## 中文简介

AWS: ECS 的 CDK 构造库

## 安装

```sh
npm install @aws-cdk/aws-ecs
```

也可以使用：`pnpm add @aws-cdk/aws-ecs`、`yarn add @aws-cdk/aws-ecs`、`bun add @aws-cdk/aws-ecs`

## README

# Amazon ECS 构造库

* * *

![End-of-Support](https://img.shields.io/badge/End--of--Support-critical.svg?style=for-the-badge)

> AWS CDK v1在2023-06-01上达到了支持结束. 此软件包不再更新,用户应该迁移到 AWS CDK v2.
> 
> 关于如何移徙的更多信息,请参见: [_移动到 AWS CDK v2_ 指南](https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html)。 。 。 .

* * *

此软件包包含用于工作 **亚马逊弹性容器 服务** (亚马逊ECS).

亚马逊弹性集装箱服务公司(Amazon ECS)是一个完全管理的集装箱管弦服务公司.

关于亚马逊ECS的进一步资料, 见 [亚马逊ECS文档](https://docs.aws.amazon.com/ecs)

以下例子创建了亚马逊ECS集群,增加了它的能力,并且 运行其中的服务 :

```ts
declare const vpc: ec2.Vpc;

// Create an ECS cluster
const cluster = new ecs.Cluster(this, 'Cluster', {
  vpc,
});

// Add capacity to it
cluster.addCapacity('DefaultAutoScalingGroupCapacity', {
  instanceType: new ec2.InstanceType("t2.xlarge"),
  desiredCapacity: 3,
});

const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');

taskDefinition.addContainer('DefaultContainer', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 512,
});

// Instantiate an Amazon ECS Service
const ecsService = new ecs.Ec2Service(this, 'Service', {
  cluster,
  taskDefinition,
});
```

关于界定共同ECS建筑模式的一组建筑,见 `@aws-cdk/aws-ecs-patterns` 软件包.

## 发射类型: AWS Fargate vs Amazon EC2

这个库里有两套构造;一套是运行于亚马逊EC2和 一个在 AWS Fargate 上运行任务.

-   使用 `Ec2TaskDefinition` 财务报告和审定财务报表 `Ec2Service` 在您账户中运行的 Amazon EC2 实例上运行任务的构造 .
-   使用 `FargateTaskDefinition` 财务报告和审定财务报表 `FargateService` 构造以运行任务 由 AWS 为您管理的实例.
-   使用 `ExternalTaskDefinition` 财务报告和审定财务报表 `ExternalService` 构造以运行 AWS ECS 任意操作自管基础设施.

主要的区别如下:

-   **亚马逊EC2**: 实例在您控制之下。 完全控制要主机的任务 资源分配。 要求至少为 每个容器。 可以使用Host, Bridge 和 AwsVpc 网络模式. 可附加 经典负载平衡器. 可以在容器和主机之间分享数量.
-   **AWS 远门**: 在 AWS 管理实例上运行的任务, AWS 管理任务以主机 为您分配。 需要说明内存和 cpu 大小 任务定义级别。 只支持 OwsVpc 网络模式和 应用程序/网络负载平衡器。 只支持 AWS 日志驱动程序 . 许多主机特性不支持, 如添加内核能力 在容器内安装主机装置/容量.
-   **AWS ECSAny 地点**:任务由客户拥有的基础设施任何地方的AWS ECS管理。 只支持 Bridge 网络模式 。 不支持自动缩放、 负载平衡、 云映射或附件 .

关于Amazon EC2 vs AWS Fargate,网络和ECS的更多信息,请参见AWS文档: [AWS 远门](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html), (中文(简体) ), [任务联网](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-networking.html), (中文(简体) ), [东加勒比国家 任何地方](https://aws.amazon.com/ecs/anywhere/)

## 集群

A 类 `Cluster` 定义运行您的基础设施 任务。 您可以在一个集群上运行许多任务 .

以下代码创建可以运行 AWS Fargate 任务的集群 :

```ts
declare const vpc: ec2.Vpc;

const cluster = new ecs.Cluster(this, 'Cluster', {
  vpc,
});
```

以下代码使用 ARN 导入一个可用 导入 Amazon ECS 服务,或者 EC2 或 Fargate.

```ts
const clusterArn = 'arn:aws:ecs:us-east-1:012345678910:cluster/clusterName';

const cluster = ecs.Cluster.fromClusterArn(this, 'Cluster', clusterArn);
```

要使用 Amazon EC2 发射类型的任务, 您必须添加容量到 组,用于为您实例安排任务。 一般来说, 您添加一个自动缩放组, 包含运行最新实例 亚马逊ECS-优化AMI到集群. 有一种方法来构建和添加这样的 自动缩放组, 或者您可以提供定制的自动缩放组 让你自己构筑。 可能添加多个自动缩放组 有各种实例类型.

以下例子创建了亚马逊ECS集群,并增加了其容量:

```ts
declare const vpc: ec2.Vpc;

const cluster = new ecs.Cluster(this, 'Cluster', {
  vpc,
});

// Either add default capacity
cluster.addCapacity('DefaultAutoScalingGroupCapacity', {
  instanceType: new ec2.InstanceType("t2.xlarge"),
  desiredCapacity: 3,
});

// Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
  vpc,
  instanceType: new ec2.InstanceType('t2.xlarge'),
  machineImage: ecs.EcsOptimizedImage.amazonLinux(),
  // Or use Amazon ECS-Optimized Amazon Linux 2 AMI
  // machineImage: EcsOptimizedImage.amazonLinux2(),
  desiredCapacity: 3,
  // ... other options here ...
});

const capacityProvider = new ecs.AsgCapacityProvider(this, 'AsgCapacityProvider', {
  autoScalingGroup,
});
cluster.addAsgCapacityProvider(capacityProvider);
```

如果你忽略了财产 `vpc`,构造将创建一个新的VPC,有两个AZ.

默认情况下, 所有机器图像都会自动更新到最新版本 在每次部署时,导致替换您自动缩放组中的实例 如果自上次部署以来已更新了军事情报系统.

如果任务排出,ECS将透明地重新安排新的任务 实例,然后结束您的旧实例。 如果你有障碍 任务排水, 任务随实例一同终止。 为了防止这种情况,你 可以通过路过来取出非更新的 AMI `cacheInContext: true`不过一定要确定 通过使用 [光盘CLI 上下文管理命令](https://docs.aws.amazon.com/cdk/latest/guide/context.html)数字 :

```ts
declare const vpc: ec2.Vpc;
const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
  machineImage: ecs.EcsOptimizedImage.amazonLinux({ cachedInContext: true }),
  vpc,
  instanceType: new ec2.InstanceType('t2.micro'),
});
```

### 瓶装火箭

[瓶装火箭](https://aws.amazon.com/bottlerocket/) 是一个基于 Linux 的开源操作系统,即 由AWS为运行容器而建造. 您可以使用 Bottellocket AMI 启动 Amazon ECS 容器实例 .

以下例子将建立一个自我管理的亚马逊EC2能力2的能力 `c5.large` Linux 实例运行 `Bottlerocket` AMI(英语:AMI (AMI)).

以下例子将瓶子火箭容量添加到集群中:

```ts
declare const cluster: ecs.Cluster;

cluster.addCapacity('bottlerocket-asg', {
  minCapacity: 2,
  instanceType: new ec2.InstanceType('c5.large'),
  machineImage: new ecs.BottleRocketImage(),
});
```

### ARM64(格拉维顿)

要启动 ARM64 硬件实例, 您可以使用 Amazon ECS 优化 亚马逊Linux 2 (arm64) AMI. 基于 Amazon Linux 2, 推荐 AMI 用于启动由基于武装的AWS供电的EC2实例 格拉维顿处理器.

```ts
declare const cluster: ecs.Cluster;

cluster.addCapacity('graviton-cluster', {
  minCapacity: 2,
  instanceType: new ec2.InstanceType('c6g.large'),
  machineImage: ecs.EcsOptimizedImage.amazonLinux2(ecs.AmiHardwareType.ARM),
});
```

瓶装火箭也得到了支持:

```ts
declare const cluster: ecs.Cluster;

cluster.addCapacity('graviton-cluster', {
  minCapacity: 2,
  instanceType: new ec2.InstanceType('c6g.large'),
  machineImageType: ecs.MachineImageType.BOTTLEROCKET,
});
```

### 实例

要将点实例添加到集群中, 您必须指定 `spotPrice` 输入 `ecs.AddCapacityOptions` 并且可选择启用 `spotInstanceDraining` 属性.

```ts
declare const cluster: ecs.Cluster;

// Add an AutoScalingGroup with spot instances to the existing cluster
cluster.addCapacity('AsgSpot', {
  maxCapacity: 2,
  minCapacity: 2,
  desiredCapacity: 2,
  instanceType: new ec2.InstanceType('c5.xlarge'),
  spotPrice: '0.0735',
  // Enable the Automated Spot Draining support for Amazon ECS
  spotInstanceDraining: true,
});
```

### SNS 主题加密

当 `ecs.AddCapacityOptions` 您提供的一个非零 `taskDrainTime` (默认)然后创建一个SNS主题和Lambda,以确保 集群实例在结束之前已经适当地耗尽了任务。 SNS主题被自动缩放组发送到实例终止生命周期事件, 兰巴达就是为了那个事件 如果你想参与 [服务器侧加密](https://docs.aws.amazon.com/sns/latest/dg/sns-data-encryption.html) 用于此 SNS 主题 然后,您可以为此提供 KMS 密钥 `topicEncryptionKey` 财产 `ecs.AddCapacityOptions`。 。 。 .

```ts
// Given
declare const cluster: ecs.Cluster;
declare const key: kms.Key;
// Then, use that key to encrypt the lifecycle-event SNS Topic.
cluster.addCapacity('ASGEncryptedSNS', {
  instanceType: new ec2.InstanceType("t2.xlarge"),
  desiredCapacity: 3,
  topicEncryptionKey: key,
});
```

## 任务定义

任务定义描述 : **任务** 应该看起来像. 任务定义有一个或一个以上的容器;通常它有一个 主容器 _默认容器_ 是第一个添加的 到任务定义,并标出 _关键_)和可选 用于支持主要集装箱的一些辅助集装箱, 做一些事情,比如上传日志或度量表来监控服务.

使用 Amazon EC2 发射类型运行任务或服务,请使用 `Ec2TaskDefinition`对于 AWS 远门任务/服务,请使用 `FargateTaskDefinition`。对于AWS ECS来说 任何地方使用 `ExternalTaskDefinition`。这些课程 提供仅包含与每个特定发射类型相关的特性的简化API.

对a `FargateTaskDefinition`,指定任务大小(`memoryLimitMiB` 财务报告和审定财务报表 `cpu`:

```ts
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  memoryLimitMiB: 512,
  cpu: 256,
});
```

在 Fargate 平台版本1.4.0 或以后,您可指定最多 200GiB 的 [电子存储](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/fargate-task-storage.html#fargate-task-storage-pv14)数字 :

```ts
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  memoryLimitMiB: 512,
  cpu: 256,
  ephemeralStorageGiB: 100,
});
```

要在任务定义中添加容器,请拨 `addContainer()`数字 :

```ts
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  memoryLimitMiB: 512,
  cpu: 256,
});
const container = fargateTaskDefinition.addContainer("WebContainer", {
  // Use an image from DockerHub
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  // ... other options here ...
});
```

对a `Ec2TaskDefinition`数字 :

```ts
const ec2TaskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef', {
  networkMode: ecs.NetworkMode.BRIDGE,
});

const container = ec2TaskDefinition.addContainer("WebContainer", {
  // Use an image from DockerHub
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  // ... other options here ...
});
```

对于一个 `ExternalTaskDefinition`数字 :

```ts
const externalTaskDefinition = new ecs.ExternalTaskDefinition(this, 'TaskDef');

const container = externalTaskDefinition.addContainer("WebContainer", {
  // Use an image from DockerHub
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  // ... other options here ...
});
```

在任务定义中添加容器属性时,或者使用各种方法,例如:

在任务定义中添加一个容器时, 请指定 `portMappings` 选项 :

```ts
declare const taskDefinition: ecs.TaskDefinition;

taskDefinition.addContainer("WebContainer", {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  portMappings: [{ containerPort: 3000 }],
});
```

要将端口映射直接添加到容器定义中, 请调用 `addPortMappings()`数字 :

```ts
declare const container: ecs.ContainerDefinition;

container.addPortMappings({
  containerPort: 3000,
});
```

要将数据卷添加到任务定义中, 请调用 `addVolume()`数字 :

```ts
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  memoryLimitMiB: 512,
  cpu: 256,
});
const volume = {
  // Use an Elastic FileSystem
  name: "mydatavolume",
  efsVolumeConfiguration: {
    fileSystemId: "EFS",
    // ... other options here ...
  },
};

const container = fargateTaskDefinition.addVolume(volume);
```

> 注:ECS。 任务定义中任何地方都不支持音量附件 .

使用一个可用 Amazon EC2 或 AWS 远门发射类型,使用 `TaskDefinition` 构造.

当创建任务定义时,您必须指定什么类型 您打算运行的任务 : Amazon EC2, AWS Fargate, 或两者兼有. 以下例子同时使用:

```ts
const taskDefinition = new ecs.TaskDefinition(this, 'TaskDef', {
  memoryMiB: '512',
  cpu: '256',
  networkMode: ecs.NetworkMode.AWS_VPC,
  compatibility: ecs.Compatibility.EC2_AND_FARGATE,
});
```

### 图像

图像提供在容器内运行的软件. 图像可以是 从 DockerHub 或 ECR 寄存器获取,直接取自本地 Docker 文件,或使用已存在的柏油球.

-   `ecs.ContainerImage.fromRegistry(imageName)`:使用公众形象.
-   `ecs.ContainerImage.fromRegistry(imageName, { credentials: mySecret })`:使用需要证书的私人图像.
-   `ecs.ContainerImage.fromEcrRepository(repo, tagOrDigest)`: 使用给定的ECR寄存器作为图像 开始 如果不提供标签或文摘,则假定“最晚”.
-   `ecs.ContainerImage.fromAsset('./image')`: 构建并上传一个 图像直接取自 a `Dockerfile` 在您的源目录中.
-   `ecs.ContainerImage.fromDockerImageAsset(asset)`: 使用已有的 `@aws-cdk/aws-ecr-assets.DockerImageAsset` 作为容器图像.
-   `ecs.ContainerImage.fromTarball(file)`: 使用已存在的柏油球.
-   `new ecs.TagParameterContainerImage(repository)`: 使用给定的ECR寄存器作为图像 但作为标记的 CloudFormation 参数.

### 环境变量

要将环境变量传递到容器,您可以使用 `environment`, (中文(简体) ), `environmentFiles`,以及 `secrets` 道具来.

```ts
declare const secret: secretsmanager.Secret;
declare const dbSecret: secretsmanager.Secret;
declare const parameter: ssm.StringParameter;
declare const taskDefinition: ecs.TaskDefinition;
declare const s3Bucket: s3.Bucket;

const newContainer = taskDefinition.addContainer('container', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  environment: { // clear text, not for sensitive data
    STAGE: 'prod',
  },
  environmentFiles: [ // list of environment files hosted either on local disk or S3
    ecs.EnvironmentFile.fromAsset('./demo-env-file.env'),
    ecs.EnvironmentFile.fromBucket(s3Bucket, 'assets/demo-env-file.env'),
  ],
  secrets: { // Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store at container start-up.
    SECRET: ecs.Secret.fromSecretsManager(secret),
    DB_PASSWORD: ecs.Secret.fromSecretsManager(dbSecret, 'password'), // Reference a specific JSON field, (requires platform version 1.4.0 or later for Fargate tasks)
    API_KEY: ecs.Secret.fromSecretsManagerVersion(secret, { versionId: '12345' }, 'apiKey'), // Reference a specific version of the secret by its version id or version stage (requires platform version 1.4.0 or later for Fargate tasks)
    PARAMETER: ecs.Secret.fromSsmParameter(parameter),
  },
});
newContainer.addEnvironment('QUEUE_NAME', 'MyQueue');
```

任务执行角色在密/参数上自动获得读取权限. 环境支助 文件仅限于S3上托管的文件的EC2发射类型. AWS文件中提供的进一步详情 关于 [指定环境变量](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/taskdef-envfiles.html)。 。 。 .

### 系统控制

要设置容器上的系统控制(内核参数),请使用 `systemControls` 道具 :

```ts
declare const taskDefinition: ecs.TaskDefinition;

taskDefinition.addContainer('container', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  systemControls: [
    {
      namespace: 'net',
      value: 'ipv4.tcp_tw_recycle',
    },
  ],
});
```

### 在 Fargate 上使用 Windows 容器

AWS Fargate支持亚马逊ECS Windows容器. 详情请见此 [博客文章](https://aws.amazon.com/tw/blogs/containers/running-windows-containers-with-amazon-ecs-on-aws-fargate/)

```ts
// Create a Task Definition for the Windows container to start
const taskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  runtimePlatform: {
    operatingSystemFamily: ecs.OperatingSystemFamily.WINDOWS_SERVER_2019_CORE,
    cpuArchitecture: ecs.CpuArchitecture.X86_64,
  },
  cpu: 1024,
  memoryLimitMiB: 2048,
});

taskDefinition.addContainer('windowsservercore', {
  logging: ecs.LogDriver.awsLogs({ streamPrefix: 'win-iis-on-fargate' }),
  portMappings: [{ containerPort: 80 }],
  image: ecs.ContainerImage.fromRegistry('mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019'),
});
```

### 使用 Graviton2 与 Fargate

AWS Graviton2支持AWS远门. 详情请见此 [博客文章](https://aws.amazon.com/blogs/aws/announcing-aws-graviton2-support-for-aws-fargate-get-up-to-40-better-price-performance-for-your-serverless-containers/)

```ts
// Create a Task Definition for running container on Graviton Runtime.
const taskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  runtimePlatform: {
    operatingSystemFamily: ecs.OperatingSystemFamily.LINUX,
    cpuArchitecture: ecs.CpuArchitecture.ARM64,
  },
  cpu: 1024,
  memoryLimitMiB: 2048,
});

taskDefinition.addContainer('webarm64', {
  logging: ecs.LogDriver.awsLogs({ streamPrefix: 'graviton2-on-fargate' }),
  portMappings: [{ containerPort: 80 }],
  image: ecs.ContainerImage.fromRegistry('public.ecr.aws/nginx/nginx:latest-arm64v8'),
});
```

## 服务

A 类 `Service` 即时 `TaskDefinition` 编号 `Cluster` 特定数量 时间,可以选择将其与负载平衡器连接. 如果任务失败, Amazon ECS 自动重启任务.

```ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  desiredCount: 5,
});
```

东加勒比国家 任何地方的服务定义看起来像:

```ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.ExternalService(this, 'Service', {
  cluster,
  taskDefinition,
  desiredCount: 5,
});
```

`Services` 默认情况下,如果不提供担保组,则将创建一个担保组. 如果您想要指定使用哪个安全小组,您可以覆盖 `securityGroups` 属性.

### 部署断路和回滚

亚马逊ECS [部署断路器](https://aws.amazon.com/tw/blogs/containers/announcing-amazon-ecs-deployment-circuit-breaker/) 自动减少不健康的服务部署,而不需要人工干预。 使用 `circuitBreaker` 启用 部署断路器和可选启用 `rollback` 自动回滚。 见 [使用部署断路器](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-type-ecs.html) 更多细节.

```ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  circuitBreaker: { rollback: true },
});
```

> 注:ECS。 任何地方不支持部署断路器和回滚器.

### 包含应用程序/网络负载平衡器

`Services` 是负载平衡目标,可以添加到目标组中,该目标组将附在应用程序/网络负载平衡器上:

```ts
declare const vpc: ec2.Vpc;
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
const service = new ecs.FargateService(this, 'Service', { cluster, taskDefinition });

const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', { vpc, internetFacing: true });
const listener = lb.addListener('Listener', { port: 80 });
const targetGroup1 = listener.addTargets('ECS1', {
  port: 80,
  targets: [service],
});
const targetGroup2 = listener.addTargets('ECS2', {
  port: 80,
  targets: [service.loadBalancerTarget({
    containerName: 'MyContainer',
    containerPort: 8080
  })],
});
```

> 注:ECS。 任何地方都不支持应用程序/网络负载平衡器.

注意在上述例子中,默认 `service` 只允许您在容器上注册第一个基本容器或第一个绘制的端口作为目标,并添加到一个新的目标群体中。 要对哪个容器和端口进行更多的控制以登记为目标,可以使用 `service.loadBalancerTarget()` 返回特定容器和港口的负载平衡目标.

或者,您也可以创建所有在此服务中注册的负载平衡器目标,将其添加到目标组中,并相应地将目标组附加到听众中.

```ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const vpc: ec2.Vpc;
const service = new ecs.FargateService(this, 'Service', { cluster, taskDefinition });

const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', { vpc, internetFacing: true });
const listener = lb.addListener('Listener', { port: 80 });
service.registerLoadBalancerTargets(
  {
    containerName: 'web',
    containerPort: 80,
    newTargetGroupId: 'ECS',
    listener: ecs.ListenerConfig.applicationListener(listener, {
      protocol: elbv2.ApplicationProtocol.HTTPS
    }),
  },
);
```

### 使用不同堆栈的负载平衡器

如果您想要将您的负载平衡器和服务器装入负载平衡器 不同的堆栈, 您可能无法使用方便方法 `loadBalancer.addListener()` 财务报告和审定财务报表 `listener.addTargets()`。 。 。 .

原因是,这些方法将创造资源 在同一 Stack 与 它们被调用的对象,这可能导致堆栈之间的循环引用. 相反,你将不得不创建一个 `ApplicationListener` 在服务堆, 或为空 `TargetGroup` 在您附加的负载平衡堆栈中 服务.

见 [ecs/cross-stack-load-ball-均衡实例](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/cross-stack-load-balancer/) 对于替代品.

### 包含经典负载平衡器

`Services` 也可直接附在经典负载平衡器上作为目标:

```ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const vpc: ec2.Vpc;
const service = new ecs.Ec2Service(this, 'Service', { cluster, taskDefinition });

const lb = new elb.LoadBalancer(this, 'LB', { vpc });
lb.addListener({ externalPort: 80 });
lb.addTarget(service);
```

同样,如果想要对负载平衡器的目标设定有更大的控制:

```ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const vpc: ec2.Vpc;
const service = new ecs.Ec2Service(this, 'Service', { cluster, taskDefinition });

const lb = new elb.LoadBalancer(this, 'LB', { vpc });
lb.addListener({ externalPort: 80 });
lb.addTarget(service.loadBalancerTarget({
  containerName: 'MyContainer',
  containerPort: 80,
}));
```

有两种更高层次的构造,包括一个供您使用的负载平衡器,可以在aws-ecs-patterns模块中找到:

-   `LoadBalancedFargateService`
-   `LoadBalancedEc2Service`

## 任务自动缩放

您可以配置服务的任务计数以匹配需求 。 任务自动缩放 通过调用配置 `autoScaleTaskCount()`数字 :

```ts
declare const target: elbv2.ApplicationTargetGroup;
declare const service: ecs.BaseService;
const scaling = service.autoScaleTaskCount({ maxCapacity: 10 });
scaling.scaleOnCpuUtilization('CpuScaling', {
  targetUtilizationPercent: 50,
});

scaling.scaleOnRequestCount('RequestScaling', {
  requestsPerTarget: 10000,
  targetGroup: target,
});
```

任务自动缩放由 _应用程序自动缩放_。 。 。 . 详情见该节.

## 与云表事件整合

为了启动亚马逊ECS任务,在亚马逊EC2支持的集群上,即时启动一个 `@aws-cdk/aws-events-targets.EcsTask` 而不是一个 `Ec2Service`数字 :

```ts
declare const cluster: ecs.Cluster;
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromAsset(path.resolve(__dirname, '..', 'eventhandler-image')),
  memoryLimitMiB: 256,
  logging: new ecs.AwsLogDriver({ streamPrefix: 'EventDemo', mode: ecs.AwsLogDriverMode.NON_BLOCKING }),
});

// An Rule that describes the event trigger (in this case a scheduled run)
const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.expression('rate(1 min)'),
});

// Pass an environment variable to the container 'TheContainer' in the task
rule.addTarget(new targets.EcsTask({
  cluster,
  taskDefinition,
  taskCount: 1,
  containerOverrides: [{
    containerName: 'TheContainer',
    environment: [{
      name: 'I_WAS_TRIGGERED',
      value: 'From CloudWatch Events'
    }],
  }],
}));
```

## 日志驱动程序

目前支持的日志驱动程序 :

-   缩写
-   流利
-   精灵
-   日记
-   json 文件
-   喷出
-   系统日志
-   asfirelens (英语)
-   常规

### 日志驱动程序

```ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.awsLogs({ streamPrefix: 'EventDemo' }),
});
```

### 流利日志驱动程序

```ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.fluentd(),
});
```

### gelf 日志驱动程序

```ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.gelf({ address: 'my-gelf-address' }),
});
```

### 日志驱动程序

```ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.journald(),
});
```

### json 文件日志驱动程序

```ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.jsonFile(),
});
```

### splunk 日志驱动程序

```ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.splunk({
    token: SecretValue.secretsManager('my-splunk-token'),
    url: 'my-splunk-url',
  }),
});
```

### syslog 日志驱动程序

```ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.syslog(),
});
```

### firelens 日志驱动程序

```ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.firelens({
    options: {
        Name: 'firehose',
        region: 'us-west-2',
        delivery_stream: 'my-stream',
    },
  }),
});
```

要将机密传递给日志配置, 请使用 `secretOptions` 属性。 任务执行角色在密/参数上自动获得读取权限.

```ts
declare const secret: secretsmanager.Secret;
declare const parameter: ssm.StringParameter;

const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.firelens({
    options: {
      // ... log driver options here ...
    },
    secretOptions: { // Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store
      apikey: ecs.Secret.fromSecretsManager(secret),
      host: ecs.Secret.fromSsmParameter(parameter),
    },
  }),
});
```

### 通用日志驱动程序

一个通用的日志驱动程序对象存在,以提供日志驱动程序配置的下级抽象.

```ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: new ecs.GenericLogDriver({
    logDriver: 'fluentd',
    options: {
      tag: 'example-tag',
    },
  }),
});
```

## CloudMap 服务发现

要使用 CloudMap 服务登记簿注册您的ECS 服务,您可以添加 `cloudMapOptions` 为您服务的财产 :

```ts
declare const taskDefinition: ecs.TaskDefinition;
declare const cluster: ecs.Cluster;

const service = new ecs.Ec2Service(this, 'Service', {
  cluster,
  taskDefinition,
  cloudMapOptions: {
    // Create A records - useful for AWSVPC network mode.
    dnsRecordType: cloudmap.DnsRecordType.A,
  },
});
```

与 `bridge` 或者说 `host` 网络模式,仅限 `SRV` DNS记录类型得到支持. 默认, `SRV` DNS 记录类型将瞄准默认的容器和默认 端口 。 不过,您可针对不同的集装箱和港口执行同样的ECS任务:

```ts
declare const taskDefinition: ecs.TaskDefinition;
declare const cluster: ecs.Cluster;

// Add a container to the task definition
const specificContainer = taskDefinition.addContainer('Container', {
  image: ecs.ContainerImage.fromRegistry('/aws/aws-example-app'),
  memoryLimitMiB: 2048,
});

// Add a port mapping
specificContainer.addPortMappings({
  containerPort: 7600,
  protocol: ecs.Protocol.TCP,
});

new ecs.Ec2Service(this, 'Service', {
  cluster,
  taskDefinition,
  cloudMapOptions: {
    // Create SRV records - useful for bridge networking
    dnsRecordType: cloudmap.DnsRecordType.SRV,
    // Targets port TCP port 7600 `specificContainer`
    container: specificContainer,
    containerPort: 7600,
  },
});
```

### 特定云映射服务协理

您可将ECS服务与特定的CloudMap服务联系起来。 来 这个,用服务 `associateCloudMapService` 方法 :

```ts
declare const cloudMapService: cloudmap.Service;
declare const ecsService: ecs.FargateService;

ecsService.associateCloudMapService({
  service: cloudMapService,
});
```

## 能力提供者

能力提供者有两大家庭: [自动取款机 远端](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/fargate-capacity-providers.html) (包括远门点)和EC2 [自动缩放 组](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/asg-capacity-providers.html) 能力提供者。 两者都得到了支持.

### 外包能力供应商

要启用 Fargate 容量提供者, 您可以设置 `enableFargateCapacityProviders` 改为 `true` 当创建您的集群时,或 援引 `enableFargateCapacityProviders()` 创建后的方法 分组。 这又会增加两个 `FARGATE` 财务报告和审定财务报表 `FARGATE_SPOT` 现有能力 在您的集群中提供 .

```ts
declare const vpc: ec2.Vpc;

const cluster = new ecs.Cluster(this, 'FargateCPCluster', {
  vpc,
  enableFargateCapacityProviders: true,
});

const taskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef');

taskDefinition.addContainer('web', {
  image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
});

new ecs.FargateService(this, 'FargateService', {
  cluster,
  taskDefinition,
  capacityProviderStrategies: [
    {
      capacityProvider: 'FARGATE_SPOT',
      weight: 2,
    },
    {
      capacityProvider: 'FARGATE',
      weight: 1,
    },
  ],
});
```

### 自动缩放组容量提供者

要添加自动缩放组容量提供者, 首先创建 EC2 自动缩放 组. 然后,创建一个 `AsgCapacityProvider` 并传递到自动缩放组 它在构造器。 然后将容量提供者添加到集群中。 终于, 您可以在服务单位或任务能力单位中以提供商的名义提及 供应商战略.

默认情况下, Auto 缩放组容量提供者将管理 Auto 缩放 集团的大小给你。 它还将促成对终止合同的统筹保护 以阻止 EC2 自动缩放终止有任务的 EC2 实例 运行在他们身上。 如果您想要禁用此行为, 请同时设置 `enableManagedScaling` 改为 `enableManagedTerminationProtection` 改为 `false`。 。 。 .

```ts
declare const vpc: ec2.Vpc;

const cluster = new ecs.Cluster(this, 'Cluster', {
  vpc,
});

const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
  vpc,
  instanceType: new ec2.InstanceType('t2.micro'),
  machineImage: ecs.EcsOptimizedImage.amazonLinux2(),
  minCapacity: 0,
  maxCapacity: 100,
});

const capacityProvider = new ecs.AsgCapacityProvider(this, 'AsgCapacityProvider', {
  autoScalingGroup,
});
cluster.addAsgCapacityProvider(capacityProvider);

const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');

taskDefinition.addContainer('web', {
  image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  memoryReservationMiB: 256,
});

new ecs.Ec2Service(this, 'EC2Service', {
  cluster,
  taskDefinition,
  capacityProviderStrategies: [
    {
      capacityProvider: capacityProvider.capacityProviderName,
      weight: 1,
    },
  ],
});
```

## 弹性推论加速器

目前,该功能仅用于EC2发射类型的服务.

在您的 EC2 实例中添加弹性推论加速器, 请先添加 `inferenceAccelerators` 字段到 Ec2 任务定义并设置 `deviceName` 财务报告和审定财务报表 `deviceType` 属性.

```ts
const inferenceAccelerators = [{
  deviceName: 'device1',
  deviceType: 'eia2.medium',
}];

const taskDefinition = new ecs.Ec2TaskDefinition(this, 'Ec2TaskDef', {
  inferenceAccelerators,
});
```

为了能够使用容器中的推论加速器,添加 `inferenceAcceleratorResources` 字段并将其设置为用于推论加速器的设备名称列表。 数字 列表应匹配 `DeviceName` 用于 `InferenceAccelerator` 在任务定义中指定.

```ts
declare const taskDefinition: ecs.TaskDefinition;
const inferenceAcceleratorResources = ['device1'];

taskDefinition.addContainer('cont', {
  image: ecs.ContainerImage.fromRegistry('test'),
  memoryLimitMiB: 1024,
  inferenceAcceleratorResources,
});
```

## ECS 执行命令

请注意,ECS Exec利用AWS系统管理器(SSM). 所以作为执行命令的先决条件 要工作,需要在当地安装 AWS CLI 的 SSM 插件。 更多信息见 [AWS CLI 安装会话管理器插件](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html)。 。 。 .

要启用您的容器的ECS Exec 特性, 请设置布尔旗 `enableExecuteCommand` 改为 `true` 内  `Ec2Service` 或者说 `FargateService`。 。 。 .

```ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.Ec2Service(this, 'Service', {
  cluster,
  taskDefinition,
  enableExecuteCommand: true,
});
```

### 启用日志

您可以通过配置将执行会话命令的日志发送到 CloudWatch 日志组或 S3 桶 页:1 `executeCommandConfiguration` 属性。 默认配置将发送 使用 `awslogs` 在任务定义中配置的日志驱动程序 。 请注意:, 当使用自己的 `logConfiguration` 必须创建指定的日志组或 S3 Bucket .

要使用您的 KMS 客户端密钥( CMK) 加密数据, 您必须创建 CMK 并提供其中的密钥 `kmsKey` 字段 会 议 日 程 和 议 程 `executeCommandConfiguration`。要使用此密钥加密 Cloud Watch 日志数据或 S3 桶,请确保连接密钥 创造资源.

```ts
declare const vpc: ec2.Vpc;
const kmsKey = new kms.Key(this, 'KmsKey');

// Pass the KMS key in the `encryptionKey` field to associate the key to the log group
const logGroup = new logs.LogGroup(this, 'LogGroup', {
  encryptionKey: kmsKey,
});

// Pass the KMS key in the `encryptionKey` field to associate the key to the S3 bucket
const execBucket = new s3.Bucket(this, 'EcsExecBucket', {
  encryptionKey: kmsKey,
});

const cluster = new ecs.Cluster(this, 'Cluster', {
  vpc,
  executeCommandConfiguration: {
    kmsKey,
    logConfiguration: {
      cloudWatchLogGroup: logGroup,
      cloudWatchEncryptionEnabled: true,
      s3Bucket: execBucket,
      s3EncryptionEnabled: true,
      s3KeyPrefix: 'exec-command-output',
    },
    logging: ecs.ExecuteCommandLogging.OVERRIDE,
  },
});
```

## 常见问题

### @aws-cdk/aws-ecs 是什么？

AWS: ECS 的 CDK 构造库注意：该包已被作者标记为弃用——AWS CDK v1 has reached End-of-Support on 2023-06-01\. This package is no longer being updated, and users should migrate to AWS CDK v2\. For more information on how to migrate, see https://docs\.aws\.amazon\.com/cdk/v2/guide/migrating-v2\.html

### 如何安装 @aws-cdk/aws-ecs？

在项目目录运行 npm install @aws-cdk/aws-ecs，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@aws-cdk/aws-applicationautoscaling（1\.204\.0）、@aws-cdk/aws-autoscaling（1\.204\.0）、@aws-cdk/aws-autoscaling-hooktargets（1\.204\.0）、@aws-cdk/aws-certificatemanager（1\.204\.0）、@aws-cdk/aws-cloudwatch（1\.204\.0）、@aws-cdk/aws-ec2（1\.204\.0）、@aws-cdk/aws-ecr（1\.204\.0）、@aws-cdk/aws-ecr-assets（1\.204\.0）、@aws-cdk/aws-elasticloadbalancing（1\.204\.0）、@aws-cdk/aws-elasticloadbalancingv2（1\.204\.0）、@aws-cdk/aws-iam（1\.204\.0）、@aws-cdk/aws-kms（1\.204\.0）、@aws-cdk/aws-lambda（1\.204\.0）、@aws-cdk/aws-logs（1\.204\.0）、@aws-cdk/aws-route53（1\.204\.0）、@aws-cdk/aws-route53-targets（1\.204\.0）、@aws-cdk/aws-s3（1\.204\.0）、@aws-cdk/aws-s3-assets（1\.204\.0）、@aws-cdk/aws-secretsmanager（1\.204\.0）、@aws-cdk/aws-servicediscovery（1\.204\.0）、@aws-cdk/aws-sns（1\.204\.0）、@aws-cdk/aws-sqs（1\.204\.0）、@aws-cdk/aws-ssm（1\.204\.0）、@aws-cdk/core（1\.204\.0）、@aws-cdk/cx-api（1\.204\.0）、constructs（^3\.3\.69）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @aws-cdk/aws-ecs 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @aws-cdk/aws-ecs 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @aws-cdk/aws-ecs 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>= 14\.15\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @aws-cdk/aws-ecs 可以商用吗？

@aws-cdk/aws-ecs 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @aws-cdk/aws-ecs 的下载量有多少？

根据 npm 官方下载统计，@aws-cdk/aws-ecs 在 2026/10/07 – 2026/11/05 这 30 天内被下载 117,748 次，日均约 3,925 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @aws-cdk/aws-ecs 还在维护吗？

最新版本 1\.204\.0 发布于 2023/06/20（3 年前）；至今共发布 288 个版本，其中过去 12 个月发布了 0 个；首次发布于 2018/07/31。作者已将其标记为弃用，新项目建议寻找替代方案。

