ContainerDefinition

class aws_cdk.aws_ecs.ContainerDefinition(scope, id, *, task_definition, image, command=None, container_name=None, cpu=None, credential_specs=None, disable_networking=None, dns_search_domains=None, dns_servers=None, docker_labels=None, docker_security_options=None, enable_restart_policy=None, entry_point=None, environment=None, environment_files=None, essential=None, extra_hosts=None, gpu_count=None, health_check=None, hostname=None, inference_accelerator_resources=None, interactive=None, linux_parameters=None, logging=None, memory_limit_mib=None, memory_reservation_mib=None, port_mappings=None, privileged=None, pseudo_terminal=None, readonly_root_filesystem=None, restart_attempt_period=None, restart_ignored_exit_codes=None, secrets=None, start_timeout=None, stop_timeout=None, system_controls=None, ulimits=None, user=None, working_directory=None)

Bases: Construct

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

ExampleMetadata:

infused

Example:

# task_definition: ecs.TaskDefinition
# cluster: ecs.Cluster


# Add a container to the task definition
specific_container = task_definition.add_container("Container",
    image=ecs.ContainerImage.from_registry("/aws/aws-example-app"),
    memory_limit_mi_b=2048
)

# Add a port mapping
specific_container.add_port_mappings(
    container_port=7600,
    protocol=ecs.Protocol.TCP
)

ecs.Ec2Service(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    cloud_map_options=ecs.CloudMapOptions(
        # Create SRV records - useful for bridge networking
        dns_record_type=cloudmap.DnsRecordType.SRV,
        # Targets port TCP port 7600 `specificContainer`
        container=specific_container,
        container_port=7600
    )
)

Constructs a new instance of the ContainerDefinition class.

Parameters:
  • scope (Construct) –

  • id (str) –

  • task_definition (TaskDefinition) – The name of the task definition that includes this container definition. [disable-awslint:ref-via-interface]

  • image (ContainerImage) – 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

  • command (Optional[Sequence[str]]) – The command that is passed to the container. If you provide a shell command as a single string, you have to quote command-line arguments. Default: - CMD value built into container image.

  • container_name (Optional[str]) – The name of the container. Default: - id of node associated with ContainerDefinition.

  • cpu (Union[int, float, None]) – The minimum number of CPU units to reserve for the container. Default: - No minimum CPU units reserved.

  • credential_specs (Optional[Sequence[CredentialSpec]]) – A list of ARNs in SSM or Amazon S3 to a credential spec (CredSpec) file that configures the container for Active Directory authentication. We recommend that you use this parameter instead of the dockerSecurityOptions. Currently, only one credential spec is allowed per container definition. Default: - No credential specs.

  • disable_networking (Optional[bool]) – Specifies whether networking is disabled within the container. When this parameter is true, networking is disabled within the container. Default: false

  • dns_search_domains (Optional[Sequence[str]]) – A list of DNS search domains that are presented to the container. Default: - No search domains.

  • dns_servers (Optional[Sequence[str]]) – A list of DNS servers that are presented to the container. Default: - Default DNS servers.

  • docker_labels (Optional[Mapping[str, str]]) – A key/value map of labels to add to the container. Default: - No labels.

  • docker_security_options (Optional[Sequence[str]]) – A list of strings to provide custom labels for SELinux and AppArmor multi-level security systems. Default: - No security labels.

  • enable_restart_policy (Optional[bool]) – Enable a restart policy for a container. When you set up a restart policy, Amazon ECS can restart the container without needing to replace the task. Default: - false unless restartIgnoredExitCodes or restartAttemptPeriod is set.

  • entry_point (Optional[Sequence[str]]) – The ENTRYPOINT value to pass to the container. Default: - Entry point configured in container.

  • environment (Optional[Mapping[str, str]]) – The environment variables to pass to the container. Default: - No environment variables.

  • environment_files (Optional[Sequence[EnvironmentFile]]) – The environment files to pass to the container. Default: - No environment files.

  • essential (Optional[bool]) – 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. Default: true

  • extra_hosts (Optional[Mapping[str, str]]) – A list of hostnames and IP address mappings to append to the /etc/hosts file on the container. Default: - No extra hosts.

  • gpu_count (Union[int, float, None]) – The number of GPUs assigned to the container. Default: - No GPUs assigned.

  • health_check (Union[HealthCheck, Dict[str, Any], None]) – The health check command and associated configuration parameters for the container. Default: - Health check configuration from container.

  • hostname (Optional[str]) – The hostname to use for your container. Default: - Automatic hostname.

  • inference_accelerator_resources (Optional[Sequence[str]]) – The inference accelerators referenced by the container. Default: - No inference accelerators assigned.

  • interactive (Optional[bool]) – When this parameter is true, you can deploy containerized applications that require stdin or a tty to be allocated. Default: - false

  • linux_parameters (Optional[LinuxParameters]) – Linux-specific modifications that are applied to the container, such as Linux kernel capabilities. For more information see KernelCapabilities. Default: - No Linux parameters.

  • logging (Optional[LogDriver]) – The log configuration specification for the container. Default: - Containers use the same logging driver that the Docker daemon uses.

  • memory_limit_mib (Union[int, float, None]) – The amount (in MiB) of memory to present to the container. 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. Default: - No memory limit.

  • memory_reservation_mib (Union[int, float, None]) – The soft limit (in MiB) of memory to reserve for the container. 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. Default: - No memory reserved.

  • port_mappings (Optional[Sequence[Union[PortMapping, Dict[str, Any]]]]) – The port mappings to add to the container definition. Default: - No ports are mapped.

  • privileged (Optional[bool]) – 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). Default: false

  • pseudo_terminal (Optional[bool]) – 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. Default: - false

  • readonly_root_filesystem (Optional[bool]) – When this parameter is true, the container is given read-only access to its root file system. Default: false

  • restart_attempt_period (Optional[Duration]) – A period of time that the container must run for before a restart can be attempted. 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. Default: - Duration.seconds(300) if enableRestartPolicy is true, otherwise no period.

  • restart_ignored_exit_codes (Optional[Sequence[Union[int, float]]]) – A list of exit codes that Amazon ECS will ignore and not attempt a restart on. This property can’t be used if enableRestartPolicy is set to false. You can specify a maximum of 50 container exit codes. Default: - No exit codes are ignored.

  • secrets (Optional[Mapping[str, Secret]]) – The secret environment variables to pass to the container. Default: - No secret environment variables.

  • start_timeout (Optional[Duration]) – Time duration (in seconds) to wait before giving up on resolving dependencies for a container. Default: - none

  • stop_timeout (Optional[Duration]) – Time duration (in seconds) to wait before the container is forcefully killed if it doesn’t exit normally on its own. Default: - none

  • system_controls (Optional[Sequence[Union[SystemControl, Dict[str, Any]]]]) – A list of namespaced kernel parameters to set in the container. Default: - No system controls are set.

  • ulimits (Optional[Sequence[Union[Ulimit, Dict[str, Any]]]]) – An array of ulimits to set in the container.

  • user (Optional[str]) – 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. Default: root

  • working_directory (Optional[str]) – The working directory in which to run commands inside the container. Default: /

Methods

add_container_dependencies(*container_dependencies)

This method adds one or more container dependencies to the container.

Parameters:

container_dependencies (ContainerDependency) –

Return type:

None

add_docker_label(name, value)

This method adds a Docker label to the container.

Parameters:
  • name (str) –

  • value (str) –

Return type:

None

add_environment(name, value)

This method adds an environment variable to the container.

Parameters:
  • name (str) –

  • value (str) –

Return type:

None

add_inference_accelerator_resource(*inference_accelerator_resources)

This method adds one or more resources to the container.

Parameters:

inference_accelerator_resources (str) –

Return type:

None

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.

Parameters:
Return type:

None

add_mount_points(*mount_points)

This method adds one or more mount points for data volumes to the container.

Parameters:

mount_points (MountPoint) –

Return type:

None

add_port_mappings(*port_mappings)

This method adds one or more port mappings to the container.

Parameters:

port_mappings (PortMapping) –

Return type:

None

add_scratch(*, container_path, name, read_only, source_path)

This method mounts temporary disk space to the container.

This adds the correct container mountPoint and task definition volume.

Parameters:
  • container_path (str) – The path on the container to mount the scratch volume at.

  • name (str) – The name of the scratch volume to mount. Must be a volume name referenced in the name parameter of task definition volume.

  • read_only (bool) – Specifies whether to give the container read-only access to the scratch volume. If this value is true, the container has read-only access to the scratch volume. If this value is false, then the container can write to the scratch volume.

  • source_path (str) –

Return type:

None

add_secret(name, secret)

This method adds a secret as environment variable to the container.

Parameters:
  • name (str) –

  • secret (Secret) –

Return type:

None

add_to_execution_policy(statement)

This method adds the specified statement to the IAM task execution policy in the task definition.

Parameters:

statement (PolicyStatement) –

Return type:

None

add_ulimits(*ulimits)

This method adds one or more ulimits to the container.

Parameters:

ulimits (Ulimit) –

Return type:

None

add_volumes_from(*volumes_from)

This method adds one or more volumes to the container.

Parameters:

volumes_from (VolumeFrom) –

Return type:

None

find_port_mapping(container_port, protocol)

Returns the host port for the requested container port if it exists.

Parameters:
  • container_port (Union[int, float]) –

  • protocol (Protocol) –

Return type:

Optional[PortMapping]

find_port_mapping_by_name(name)

Returns the port mapping with the given name, if it exists.

Parameters:

name (str) –

Return type:

Optional[PortMapping]

render_container_definition(_task_definition=None)

Render this container definition to a CloudFormation object.

Parameters:

_task_definition (Optional[TaskDefinition]) – [disable-awslint:ref-via-interface] (unused but kept to avoid breaking change).

Return type:

ContainerDefinitionProperty

to_string()

Returns a string representation of this construct.

Return type:

str

Attributes

CONTAINER_PORT_USE_RANGE = 0
container_dependencies

An array dependencies defined for container startup and shutdown.

container_name

The name of this container.

container_port

The port the container will listen on.

cpu

The number of cpu units reserved for the container.

credential_specs

The crdential specifications for this container.

environment_files

The environment files for this container.

essential

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.

image_name

The name of the image referenced by this container.

ingress_port

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.

linux_parameters

The Linux-specific modifications that are applied to the container, such as Linux kernel capabilities.

log_driver_config

The log configuration specification for the container.

memory_limit_specified

Whether there was at least one memory limit specified in this definition.

mount_points

The mount points for data volumes in your container.

node

The tree node.

port_mappings

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.

pseudo_terminal

Specifies whether a TTY must be allocated for this container.

references_secret_json_field

Whether this container definition references a specific JSON field of a secret stored in Secrets Manager.

task_definition

The name of the task definition that includes this container definition.

ulimits

An array of ulimits to set in the container.

volumes_from

The data volumes to mount from another container in the same task definition.

Static Methods

classmethod is_construct(x)

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) – Any object.

Return type:

bool

Returns:

true if x is an object created from a class which extends Construct.