# BaseService

The base class for Ec2Service and FargateService services.

Extends: Construct › Resource › BaseService
Implements: IResource, IConnectable, IBaseService, IService, ILoadBalancerTarget, IApplicationLoadBalancerTarget, INetworkLoadBalancerTarget, IEnvironmentAware, IServiceRef, IConstruct, IDependable
Superclass of: Ec2Service, ExternalService, FargateService

- Source: [`aws-ecs/lib/base/base-service.ts`](https://github.com/aws/aws-cdk/blob/v2.274.0/packages/aws-cdk-lib/aws-ecs/lib/base/base-service.ts#L728)
- Type last changed: v2.252.0 · 30 Apr 2026

## Example

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

const service = ecs.BaseService.fromServiceArnWithCluster(this, 'EcsService',
  'arn:aws:ecs:us-east-1:123456789012:service/myClusterName/myServiceName'
);
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const buildOutput = new codepipeline.Artifact();
// add source and build stages to the pipeline as usual...
const deployStage = pipeline.addStage({
  stageName: 'Deploy',
  actions: [
    new codepipeline_actions.EcsDeployAction({
      actionName: 'DeployAction',
      service: service,
      input: buildOutput,
    }),
  ],
});
```

## Initializer

```ts
new BaseService(scope: Construct, id: string, props: BaseServiceProps, additionalProps: any, taskDefinition: TaskDefinition)
```

## Construct Props

- `bakeTime`: [Duration](/cdk/api/v2/docs/aws-cdk-lib.Duration.html) = none — bake time minutes for service.

- `canaryConfiguration`: [TrafficShiftConfig](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.TrafficShiftConfig.html) — Configuration for canary deployment strategy.

  **Default:** no canary configuration

  Only valid when deploymentStrategy is set to CANARY.

- `capacityProviderStrategies`: [CapacityProviderStrategy](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.CapacityProviderStrategy.html)[] = undefined — A list of Capacity Provider strategies used to place a service.

- `circuitBreaker`: [DeploymentCircuitBreaker](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.DeploymentCircuitBreaker.html) = disabled — Whether to enable the deployment circuit breaker.

  If this property is defined, circuit breaker will be implicitly
  enabled.

- `cloudMapOptions`: [CloudMapOptions](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.CloudMapOptions.html) — The options for configuring an Amazon ECS service to use service discovery.

  **Default:** AWS Cloud Map service discovery is not enabled.

- `cluster`: [ICluster](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ICluster.html) (required) — The name of the cluster that hosts the service.

- `deploymentAlarms`: [DeploymentAlarmConfig](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.DeploymentAlarmConfig.html) — The alarm(s) to monitor during deployment, and behavior to apply if at least one enters a state of alarm during the deployment or bake time.

  **Default:** No alarms will be monitored during deployment.

- `deploymentController`: [DeploymentController](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.DeploymentController.html) — Specifies which deployment controller to use for the service.

  **Default:** Rolling update (ECS)

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

- `deploymentStrategy`: [DeploymentStrategy](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.DeploymentStrategy.html) = ROLLING — The deployment strategy to use for the service.

- `desiredCount`: number — The desired number of instantiations of the task definition to keep running on the service.

  **Default:** When creating the service, default is 1; when updating the service, default uses the current task number.

- `enableECSManagedTags`: boolean = false — Specifies whether to enable Amazon ECS managed tags for the tasks within the service.

  For more information, see
  [Tagging Your Amazon ECS Resources](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html)

- `enableExecuteCommand`: boolean = undefined — Whether to enable the ability to execute into a container.

- `forceNewDeployment`: [ForceNewDeployment](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ForceNewDeployment.html) — Configuration for forcing a new deployment of the service.

  **Default:** no forced deployment

  By default, deployments aren't forced. You can use this option to start
  a new deployment with no service definition changes. For example, you can
  update a service's tasks to use a newer Docker image with the same
  image/tag combination (`my_image:latest`) or to roll Fargate tasks onto
  a newer platform version.

  This is equivalent to calling the `forceNewDeployment()` method, but allows
  you to configure it declaratively at construction time, including the ability
  to explicitly disable it with `enabled: false`.

- `healthCheckGracePeriod`: [Duration](/cdk/api/v2/docs/aws-cdk-lib.Duration.html) — The period of time, in seconds, that the Amazon ECS service scheduler ignores unhealthy Elastic Load Balancing target health checks after a task has first started.

  **Default:** defaults to 60 seconds if at least one load balancer is in-use and it is not already set

- `launchType`: [LaunchType](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.LaunchType.html) (required) — The launch type on which to run your service.

  LaunchType will be omitted if capacity provider strategies are specified on the service.

- `lifecycleHooks`: [IDeploymentLifecycleHookTarget](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.IDeploymentLifecycleHookTarget.html)[] = none; — The lifecycle hooks to execute during deployment stages.

- `linearConfiguration`: [TrafficShiftConfig](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.TrafficShiftConfig.html) — Configuration for linear deployment strategy.

  **Default:** no linear configuration

  Only valid when deploymentStrategy is set to LINEAR.

- `maxHealthyPercent`: number — The maximum number of tasks, specified as a percentage of the Amazon ECS service's DesiredCount value, that can run in a service during a deployment.

  **Default:** 100 if daemon, otherwise 200

- `minHealthyPercent`: number — The minimum number of tasks, specified as a percentage of the Amazon ECS service's DesiredCount value, that must continue to run and remain healthy during a deployment.

  **Default:** 0 if daemon, otherwise 50

- `propagateTags`: [PropagatedTagSource](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.PropagatedTagSource.html) = PropagatedTagSource.NONE — Specifies whether to propagate the tags from the task definition or the service to the tasks in the service.

  Valid values are: PropagatedTagSource.SERVICE, PropagatedTagSource.TASK_DEFINITION or PropagatedTagSource.NONE

- `serviceConnectConfiguration`: [ServiceConnectProps](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ServiceConnectProps.html) — Configuration for Service Connect.

  **Default:** No ports are advertised via Service Connect on this service, and the service cannot make requests to other services via Service Connect.

- `serviceName`: string — The name of the service.

  **Default:** CloudFormation-generated name.

- `taskDefinitionRevision`: [TaskDefinitionRevision](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.TaskDefinitionRevision.html) — Revision number for the task definition or `latest` to use the latest active task revision.

  **Default:** Uses the revision of the passed task definition deployed by CloudFormation

- `volumeConfigurations`: [ServiceManagedVolume](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ServiceManagedVolume.html)[] = undefined — Configuration details for a volume used by the service.

  This allows you to specify
  details about the EBS volume that can be attached to ECS tasks.

## Properties

- `cloudMapService`: [IService](/cdk/api/v2/docs/aws-cdk-lib.aws_servicediscovery.IService.html) — The CloudMap service created for this service, if any.

- `cluster`: [ICluster](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ICluster.html) (required) — The cluster that hosts the service.

- `connections`: [Connections](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Connections.html) (required) — The security groups which manage the allowed network traffic for the service.

- `env`: [ResourceEnvironment](/cdk/api/v2/docs/aws-cdk-lib.interfaces.ResourceEnvironment.html) (required) — The environment this resource belongs to.

  For resources that are created and managed in a Stack (those created by
  creating new class instances like `new Role()`, `new Bucket()`, etc.), this
  is always the same as the environment of the stack they belong to.

  For referenced resources (those obtained from referencing methods like
  `Role.fromRoleArn()`, `Bucket.fromBucketName()`, etc.), they might be
  different than the stack they were imported into.

- `loadBalancers`: [CfnService.LoadBalancerProperty](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.CfnService.LoadBalancerProperty.html)[] (required) — A list of Elastic Load Balancing load balancer objects, containing the load balancer name, the container name (as it appears in a container definition), and the container port to access from the load balancer.

- `node`: [Node](/cdk/api/v2/docs/constructs.Node.html) (required) — The tree node.

- `serviceArn`: string (required) — The Amazon Resource Name (ARN) of the service.

- `serviceName`: string (required) — The name of the service.

- `serviceRef`: [ServiceReference](/cdk/api/v2/docs/aws-cdk-lib.interfaces.aws_ecs.ServiceReference.html) (required) — A reference to this service.

- `stack`: [Stack](/cdk/api/v2/docs/aws-cdk-lib.Stack.html) (required) — The stack in which this resource is defined.

- `taskDefinition`: [TaskDefinition](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.TaskDefinition.html) (required) — The task definition to use for tasks in the service.

## Methods

- `addLifecycleHook(target: IDeploymentLifecycleHookTarget): void` — Add a deployment lifecycle hook target.

  **Parameters**

  - `target` — The lifecycle hook target to add.

- `addVolume(volume: ServiceManagedVolume): void` — Adds a volume to the Service.

- `applyCrossStackReferenceStrength(strength: ReferenceStrength): void` — Override the cross-stack reference strength for this resource.

  When set, any cross-stack reference to this resource will use the specified
  mechanism instead of the global default determined by the
  `@aws-cdk/core:defaultCrossStackReferences` context key. This is useful for
  selectively weakening specific references to avoid the "deadly embrace" problem
  without changing the app-wide default.

  **Parameters**

  - `strength` — - The reference strength to use for this resource.

- `applyRemovalPolicy(policy: RemovalPolicy): void` — Apply the given removal policy to this resource.

  The Removal Policy controls what happens to this resource when it stops
  being managed by CloudFormation, either because you've removed it from the
  CDK application or because you've made a change that requires the resource
  to be replaced.

  The resource can be deleted (`RemovalPolicy.DESTROY`), or left in your AWS
  account for data recovery and cleanup later (`RemovalPolicy.RETAIN`).

- `associateCloudMapService(options: AssociateCloudMapServiceOptions): void` — Associates this service with a CloudMap service.

- `attachToApplicationTargetGroup(targetGroup: IApplicationTargetGroup): LoadBalancerTargetProps` — This method is called to attach this service to an Application Load Balancer.

  Don't call this function directly. Instead, call `listener.addTargets()`
  to add this service to a load balancer.

- `attachToClassicLB(loadBalancer: LoadBalancer): void` — Registers the service as a target of a Classic Load Balancer (CLB).

  Don't call this. Call `loadBalancer.addTarget()` instead.

  **Parameters**

  - `loadBalancer` — [disable-awslint:ref-via-interface].

- `attachToNetworkTargetGroup(targetGroup: INetworkTargetGroup): LoadBalancerTargetProps` — This method is called to attach this service to a Network Load Balancer.

  Don't call this function directly. Instead, call `listener.addTargets()`
  to add this service to a load balancer.

- `autoScaleTaskCount(props: EnableScalingProps): ScalableTaskCount` — An attribute representing the minimum and maximum task count for an AutoScalingGroup.

- `enableCloudMap(options: CloudMapOptions): Service` — Enable CloudMap service discovery for the service.

  **Returns:** The created CloudMap service

- `enableDeploymentAlarms(alarmNames: string[], options?: DeploymentAlarmOptions): void` — Enable Deployment Alarms which take advantage of arbitrary alarms and configure them after service initialization.

  If you have already enabled deployment alarms, this function can be used to tell ECS about additional alarms that
  should interrupt a deployment.

  New alarms specified in subsequent calls of this function will be appended to the existing list of alarms.

  The same Alarm Behavior must be used on all deployment alarms. If you specify different AlarmBehavior values in
  multiple calls to this function, or the Alarm Behavior used here doesn't match the one used in the service
  constructor, an error will be thrown.

  If the alarm's metric references the service, you cannot pass `Alarm.alarmName` here. That will cause a circular
  dependency between the service and its deployment alarm. See this package's README for options to alarm on service
  metrics, and avoid this circular dependency.

- `enableServiceConnect(config?: ServiceConnectProps): void` — Enable Service Connect on this service.

- `forceNewDeployment(nonce?: string): void` — Forces a new deployment of the service.

  This can be used to trigger a deployment without changing the task definition or desired count.
  ECS will start a new deployment even if there are no changes to the service configuration.

  **Important:** When called without a nonce, a timestamp is generated automatically, which means
  every `cdk synth` produces a different template and every `cdk deploy` triggers a new deployment
  regardless of whether any code has changed. To avoid this, provide a stable nonce value that only
  changes when you intentionally want to force a redeployment (e.g., an image digest or a version string).

  **Parameters**

  - `nonce` — - A unique string (1-255 characters) that signals ECS to start a new deployment.

- `fromServiceArnWithCluster(scope: Construct, id: string, serviceArn: string): IBaseService` (static) — Import an existing ECS/Fargate Service using the service cluster format.

  The format is the "new" format "arn:aws:ecs:region:aws_account_id:service/cluster-name/service-name".

- `isConstruct(x: any): boolean` (static) — Checks if `x` is a construct.

  Use this method instead of `instanceof` to properly detect `Construct`
  instances, even when the construct library is symlinked.

  Explanation: in JavaScript, multiple copies of the `constructs` library on
  disk are seen as independent, completely different libraries. As a
  consequence, the class `Construct` in each copy of the `constructs` library
  is seen as a different class, and an instance of one class will not test as
  `instanceof` the other class. `npm install` will not create installations
  like this, but users may manually symlink construct libraries together or
  use a monorepo tool: in those cases, multiple copies of the `constructs`
  library can be accidentally installed, and `instanceof` will behave
  unpredictably. It is safest to avoid using `instanceof`, and using
  this type-testing method instead.

  **Parameters**

  - `x` — Any object.

  **Returns:** true if `x` is an object created from a class which extends `Construct`.

- `isOwnedResource(construct: IConstruct): boolean` (static) — Returns true if the construct was created by CDK, and false otherwise.

- `isResource(construct: IConstruct): boolean` (static) — Check whether the given construct is a Resource.

- `isUsingECSDeploymentController(): boolean` — Checks if the service is using the ECS deployment controller.

  **Returns:** true if the service is using the ECS deployment controller or if no deployment controller is specified (defaults to ECS)

- `loadBalancerTarget(options: LoadBalancerTargetOptions): IEcsLoadBalancerTarget` — Return a load balancing target for a specific container and port.

  Use this function to create a load balancer target if you want to load balance to
  another container than the first essential container or the first mapped port on
  the container.

  Use the return value of this function where you would normally use a load balancer
  target, instead of the `Service` object itself.

  ```ts
  declare const listener: elbv2.ApplicationListener;
  declare const service: ecs.BaseService;
  listener.addTargets('ECS', {
    port: 80,
    targets: [service.loadBalancerTarget({
      containerName: 'MyContainer',
      containerPort: 1234,
    })],
  });
  ```

- `metric(metricName: string, props?: MetricOptions): Metric` — This method returns the specified CloudWatch metric name for this service.

- `metricCpuUtilization(props?: MetricOptions): Metric` — This method returns the CloudWatch metric for this service's CPU utilization.

- `metricMemoryUtilization(props?: MetricOptions): Metric` — This method returns the CloudWatch metric for this service's memory utilization.

- `registerLoadBalancerTargets(...targets: EcsTarget[]): void` — Use this function to create all load balancer targets to be registered in this service, add them to target groups, and attach target groups to listeners accordingly.

  Alternatively, you can use `listener.addTargets()` to create targets and add them to target groups.

  ```ts
  declare const listener: elbv2.ApplicationListener;
  declare const service: ecs.BaseService;
  service.registerLoadBalancerTargets(
    {
      containerName: 'web',
      containerPort: 80,
      newTargetGroupId: 'ECS',
      listener: ecs.ListenerConfig.applicationListener(listener, {
        protocol: elbv2.ApplicationProtocol.HTTPS
      }),
    },
  )
  ```

- `toString(): string` — Returns a string representation of this construct.

- `with(...mixins: IMixin[]): IConstruct` — Applies one or more mixins to this construct.

  Mixins are applied in order. The list of constructs is captured at the
  start of the call, so constructs added by a mixin will not be visited.
  Use multiple `with()` calls if subsequent mixins should apply to added
  constructs.
