# ContainerDefinition

A container definition is used in a task definition to describe the containers that are launched as part of a task.

Extends: Construct › ContainerDefinition
Implements: IConstruct, IDependable
Superclass of: FirelensLogRouter

- Source: [`aws-ecs/lib/container-definition.ts`](https://github.com/aws/aws-cdk/blob/v2.274.0/packages/aws-cdk-lib/aws-ecs/lib/container-definition.ts#L462)
- Type last changed: v2.196.0 · 16 May 2025

## Example

```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,
  minHealthyPercent: 100,
  cloudMapOptions: {
    // Create SRV records - useful for bridge networking
    dnsRecordType: cloudmap.DnsRecordType.SRV,
    // Targets port TCP port 7600 `specificContainer`
    container: specificContainer,
    containerPort: 7600,
  },
});
```

## Initializer

```ts
new ContainerDefinition(scope: Construct, id: string, props: ContainerDefinitionProps)
```

## Construct Props

- `command`: string[] — The command that is passed to the container.

  **Default:** CMD value built into container image.

  If you provide a shell command as a single string, you have to quote command-line arguments.

- `containerName`: string — The name of the container.

  **Default:** id of node associated with ContainerDefinition.

- `cpu`: number — The minimum number of CPU units to reserve for the container.

  **Default:** No minimum CPU units reserved.

- `credentialSpecs`: [CredentialSpec](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.CredentialSpec.html)[] — A list of ARNs in SSM or Amazon S3 to a credential spec (`CredSpec`) file that configures the container for Active Directory authentication.

  **Default:** No credential specs.

  We recommend that you use this parameter instead of the `dockerSecurityOptions`.

  Currently, only one credential spec is allowed per container definition.

- `disableNetworking`: boolean = false — Specifies whether networking is disabled within the container.

  When this parameter is true, networking is disabled within the container.

- `dnsSearchDomains`: string[] — A list of DNS search domains that are presented to the container.

  **Default:** No search domains.

- `dnsServers`: string[] — A list of DNS servers that are presented to the container.

  **Default:** Default DNS servers.

- `dockerLabels`: { [key: string]: string } — A key/value map of labels to add to the container.

  **Default:** No labels.

- `dockerSecurityOptions`: string[] — A list of strings to provide custom labels for SELinux and AppArmor multi-level security systems.

  **Default:** No security labels.

- `enableRestartPolicy`: boolean — Enable a restart policy for a container.

  **Default:** false unless `restartIgnoredExitCodes` or `restartAttemptPeriod` is set.

  When you set up a restart policy, Amazon ECS can restart the container without needing to replace the task.

- `entryPoint`: string[] — The ENTRYPOINT value to pass to the container.

  **Default:** Entry point configured in container.

- `environment`: { [key: string]: string } — The environment variables to pass to the container.

  **Default:** No environment variables.

- `environmentFiles`: [EnvironmentFile](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.EnvironmentFile.html)[] — The environment files to pass to the container.

  **Default:** No environment files.

- `essential`: boolean = true — Specifies whether the container is marked essential.

  If the essential parameter of a container is marked as true, and that container fails
  or stops for any reason, all other containers that are part of the task are stopped.
  If the essential parameter of a container is marked as false, then its failure does not
  affect the rest of the containers in a task. All tasks must have at least one essential container.

  If this parameter is omitted, a container is assumed to be essential.

- `extraHosts`: { [key: string]: string } — A list of hostnames and IP address mappings to append to the /etc/hosts file on the container.

  **Default:** No extra hosts.

- `gpuCount`: number — The number of GPUs assigned to the container.

  **Default:** No GPUs assigned.

- `healthCheck`: [HealthCheck](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.HealthCheck.html) — The health check command and associated configuration parameters for the container.

  **Default:** Health check configuration from container.

- `hostname`: string — The hostname to use for your container.

  **Default:** Automatic hostname.

- `image`: [ContainerImage](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ContainerImage.html) (required) — The image used to start a container.

  This string is passed directly to the Docker daemon.
  Images in the Docker Hub registry are available by default.
  Other repositories are specified with either repository-url/image:tag or repository-url/image@digest.
  TODO: Update these to specify using classes of IContainerImage

- `inferenceAcceleratorResources`: string[] — The inference accelerators referenced by the container.

  **Default:** No inference accelerators assigned.

- `interactive`: boolean = false — When this parameter is true, you can deploy containerized applications that require stdin or a tty to be allocated.

- `linuxParameters`: [LinuxParameters](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.LinuxParameters.html) — Linux-specific modifications that are applied to the container, such as Linux kernel capabilities.

  **Default:** No Linux parameters.

  For more information see [KernelCapabilities](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html).

- `logging`: [LogDriver](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.LogDriver.html) — The log configuration specification for the container.

  **Default:** Containers use the same logging driver that the Docker daemon uses.

- `memoryLimitMiB`: number — The amount (in MiB) of memory to present to the container.

  **Default:** No memory limit.

  If your container attempts to exceed the allocated memory, the container
  is terminated.

  At least one of memoryLimitMiB and memoryReservationMiB is required for non-Fargate services.

- `memoryReservationMiB`: number — The soft limit (in MiB) of memory to reserve for the container.

  **Default:** No memory reserved.

  When system memory is under heavy contention, Docker attempts to keep the
  container memory to this soft limit. However, your container can consume more
  memory when it needs to, up to either the hard limit specified with the memory
  parameter (if applicable), or all of the available memory on the container
  instance, whichever comes first.

  At least one of memoryLimitMiB and memoryReservationMiB is required for non-Fargate services.

- `portMappings`: [PortMapping](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.PortMapping.html)[] — The port mappings to add to the container definition.

  **Default:** No ports are mapped.

- `privileged`: boolean = false — Specifies whether the container is marked as privileged.

  When this parameter is true, the container is given elevated privileges on the host container instance (similar to the root user).

- `pseudoTerminal`: boolean = false — When this parameter is true, a TTY is allocated.

  This parameter maps to Tty in the "Create a container section" of the
  Docker Remote API and the --tty option to `docker run`.

- `readonlyRootFilesystem`: boolean = false — When this parameter is true, the container is given read-only access to its root file system.

- `restartAttemptPeriod`: [Duration](/cdk/api/v2/docs/aws-cdk-lib.Duration.html) — A period of time that the container must run for before a restart can be attempted.

  **Default:** Duration.seconds(300) if `enableRestartPolicy` is true, otherwise no period.

  A container can be restarted only once every `restartAttemptPeriod` seconds.
  If a container isn't able to run for this time period and exits early, it will not be restarted.

  This property can't be used if `enableRestartPolicy` is set to false.

  You can set a minimum `restartAttemptPeriod` of 60 seconds and a maximum `restartAttemptPeriod`
  of 1800 seconds.

- `restartIgnoredExitCodes`: number[] — A list of exit codes that Amazon ECS will ignore and not attempt a restart on.

  **Default:** No exit codes are ignored.

  This property can't be used if `enableRestartPolicy` is set to false.

  You can specify a maximum of 50 container exit codes.

- `secrets`: { [key: string]: [Secret](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.Secret.html) } — The secret environment variables to pass to the container.

  **Default:** No secret environment variables.

- `startTimeout`: [Duration](/cdk/api/v2/docs/aws-cdk-lib.Duration.html) = none — Time duration (in seconds) to wait before giving up on resolving dependencies for a container.

- `stopTimeout`: [Duration](/cdk/api/v2/docs/aws-cdk-lib.Duration.html) = none — Time duration (in seconds) to wait before the container is forcefully killed if it doesn't exit normally on its own.

- `systemControls`: [SystemControl](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.SystemControl.html)[] — A list of namespaced kernel parameters to set in the container.

  **Default:** No system controls are set.

- `taskDefinition`: [TaskDefinition](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.TaskDefinition.html) (required) — The name of the task definition that includes this container definition.

  [disable-awslint:ref-via-interface]

- `ulimits`: [Ulimit](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.Ulimit.html)[] — An array of ulimits to set in the container.

- `user`: string = root — The user to use inside the container.

  This parameter maps to User in the Create a container section of the Docker Remote API and the --user option to docker run.

- `versionConsistency`: [VersionConsistency](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.VersionConsistency.html) — Specifies whether Amazon ECS will resolve the container image tag provided in the container definition to an image digest.

  **Default:** VersionConsistency.DISABLED if `image` is a CDK asset, VersionConsistency.ENABLED otherwise

  If you set the value for a container as disabled, Amazon ECS will
  not resolve the provided container image tag to a digest and will use the
  original image URI specified in the container definition for deployment.

- `workingDirectory`: string = / — The working directory in which to run commands inside the container.

## Properties

- `CONTAINER_PORT_USE_RANGE`: number (required) (static)

- `containerDependencies`: [ContainerDependency](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ContainerDependency.html)[] (required) — An array dependencies defined for container startup and shutdown.

- `containerName`: string (required) — The name of this container.

- `containerPort`: number (required) — The port the container will listen on.

- `cpu`: number — The number of cpu units reserved for the container.

- `credentialSpecs`: [CredentialSpecConfig](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.CredentialSpecConfig.html)[] — The crdential specifications for this container.

- `environmentFiles`: [EnvironmentFileConfig](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.EnvironmentFileConfig.html)[] — The environment files for this container.

- `essential`: boolean (required) — Specifies whether the container will be marked essential.

  If the essential parameter of a container is marked as true, and that container
  fails or stops for any reason, all other containers that are part of the task are
  stopped. If the essential parameter of a container is marked as false, then its
  failure does not affect the rest of the containers in a task.

  If this parameter is omitted, a container is assumed to be essential.

- `imageName`: string (required) — The name of the image referenced by this container.

- `ingressPort`: number (required) — The inbound rules associated with the security group the task or service will use.

  This property is only used for tasks that use the awsvpc network mode.

- `linuxParameters`: [LinuxParameters](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.LinuxParameters.html) — The Linux-specific modifications that are applied to the container, such as Linux kernel capabilities.

- `logDriverConfig`: [LogDriverConfig](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.LogDriverConfig.html) — The log configuration specification for the container.

- `memoryLimitSpecified`: boolean (required) — Whether there was at least one memory limit specified in this definition.

- `mountPoints`: [MountPoint](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.MountPoint.html)[] (required) — The mount points for data volumes in your container.

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

- `portMappings`: [PortMapping](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.PortMapping.html)[] (required) — The list of port mappings for the container.

  Port mappings allow containers to access ports
  on the host container instance to send or receive traffic.

- `PROPERTY_INJECTION_ID`: string (required) (static) — Uniquely identifies this class.

- `pseudoTerminal`: boolean — Specifies whether a TTY must be allocated for this container.

- `referencesSecretJsonField`: boolean — Whether this container definition references a specific JSON field of a secret stored in Secrets Manager.

- `taskDefinition`: [TaskDefinition](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.TaskDefinition.html) (required) — The name of the task definition that includes this container definition.

- `ulimits`: [Ulimit](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.Ulimit.html)[] (required) — An array of ulimits to set in the container.

- `volumesFrom`: [VolumeFrom](/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.VolumeFrom.html)[] (required) — The data volumes to mount from another container in the same task definition.

## Methods

- `addContainerDependencies(...containerDependencies: ContainerDependency[]): void` — This method adds one or more container dependencies to the container.

- `addDockerLabel(name: string, value: string): void` — This method adds a Docker label to the container.

- `addEnvironment(name: string, value: string): void` — This method adds an environment variable to the container.

- `addInferenceAcceleratorResource(...inferenceAcceleratorResources: string[]): void` — This method adds one or more resources to the container.

- `addLink(container: ContainerDefinition, alias?: string): void` — This method adds a link which allows containers to communicate with each other without the need for port mappings.

  This parameter is only supported if the task definition is using the bridge network mode.
  Warning: The --link flag is a legacy feature of Docker. It may eventually be removed.

- `addMountPoints(...mountPoints: MountPoint[]): void` — This method adds one or more mount points for data volumes to the container.

- `addPortMappings(...portMappings: PortMapping[]): void` — This method adds one or more port mappings to the container.

- `addScratch(scratch: ScratchSpace): void` — This method mounts temporary disk space to the container.

  This adds the correct container mountPoint and task definition volume.

- `addSecret(name: string, secret: Secret): void` — This method adds a secret as environment variable to the container.

- `addToExecutionPolicy(statement: PolicyStatement): void` — This method adds the specified statement to the IAM task execution policy in the task definition.

- `addUlimits(...ulimits: Ulimit[]): void` — This method adds one or more ulimits to the container.

- `addVolumesFrom(...volumesFrom: VolumeFrom[]): void` — This method adds one or more volumes to the container.

- `findPortMapping(containerPort: number, protocol: Protocol): PortMapping` — Returns the host port for the requested container port if it exists.

- `findPortMappingByName(name: string): PortMapping` — Returns the port mapping with the given name, if it exists.

- `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`.

- `renderContainerDefinition(_taskDefinition?: TaskDefinition): CfnTaskDefinition.ContainerDefinitionProperty` — Render this container definition to a CloudFormation object.

  **Parameters**

  - `_taskDefinition` — [disable-awslint:ref-via-interface] (unused but kept to avoid breaking change).

- `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.

  **Parameters**

  - `mixins` — The mixins to apply.

  **Returns:** This construct for chaining
