ContainerDefinition
A container definition is used in a task definition to describe the containers that are launched as part of a task.
Example
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,
},
});
# 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,
min_healthy_percent=100,
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
)
)
TaskDefinition taskDefinition;
Cluster cluster;
// Add a container to the task definition
ContainerDefinition specificContainer = taskDefinition.addContainer("Container", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("/aws/aws-example-app"))
.memoryLimitMiB(2048)
.build());
// Add a port mapping
specificContainer.addPortMappings(PortMapping.builder()
.containerPort(7600)
.protocol(Protocol.TCP)
.build());
Ec2Service.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.cloudMapOptions(CloudMapOptions.builder()
// Create SRV records - useful for bridge networking
.dnsRecordType(DnsRecordType.SRV)
// Targets port TCP port 7600 `specificContainer`
.container(specificContainer)
.containerPort(7600)
.build())
.build();
// Install: dotnet add package Amazon.CDK.Lib
TaskDefinition taskDefinition;
Cluster cluster;
// Add a container to the task definition
var specificContainer = taskDefinition.AddContainer("Container", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("/aws/aws-example-app"),
MemoryLimitMiB = 2048
});
// Add a port mapping
specificContainer.AddPortMappings(new PortMapping {
ContainerPort = 7600,
Protocol = Protocol.TCP
});
new Ec2Service(this, "Service", new Ec2ServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
MinHealthyPercent = 100,
CloudMapOptions = new CloudMapOptions {
// Create SRV records - useful for bridge networking
DnsRecordType = DnsRecordType.SRV,
// Targets port TCP port 7600 `specificContainer`
Container = specificContainer,
ContainerPort = 7600
}
});
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var taskDefinition TaskDefinition
var cluster Cluster
// Add a container to the task definition
specificContainer := taskDefinition.AddContainer(jsii.String("Container"), &ContainerDefinitionOptions{
Image: ecs.ContainerImage_FromRegistry(jsii.String("/aws/aws-example-app")),
MemoryLimitMiB: jsii.Number(2048),
})
// Add a port mapping
specificContainer.AddPortMappings(&PortMapping{
ContainerPort: jsii.Number(7600),
Protocol: ecs.Protocol_TCP,
})
ecs.NewEc2Service(this, jsii.String("Service"), &Ec2ServiceProps{
Cluster: Cluster,
TaskDefinition: TaskDefinition,
MinHealthyPercent: jsii.Number(100),
CloudMapOptions: &CloudMapOptions{
// Create SRV records - useful for bridge networking
DnsRecordType: cloudmap.DnsRecordType_SRV,
// Targets port TCP port 7600 `specificContainer`
Container: specificContainer,
ContainerPort: jsii.Number(7600),
},
})
Initializer
new ContainerDefinition(scope: Construct, id: string, props: ContainerDefinitionProps)
ContainerDefinition(scope: Construct, id: str, props: ContainerDefinitionProps)
new ContainerDefinition(Construct scope, String id, ContainerDefinitionProps props)
new ContainerDefinition(Construct scope, string id, ContainerDefinitionProps props)
NewContainerDefinition(Scope Construct, Id *string, Props ContainerDefinitionProps)
Construct Props
commandstring[]commandtyping.List[str]commandList<String>Commandstring[]Command*[]*string= CMD value built into container i…#If you provide a shell command as a single string, you have to quote command-line arguments.
default
Default: CMD value built into container image.
containerNamestringcontainer_namestrcontainerNameStringContainerNamestringContainerName*string= id of node associated with Conta…#default
Default: id of node associated with ContainerDefinition.
credentialSpecsCredentialSpec[]credential_specstyping.List[CredentialSpec]credentialSpecsList<CredentialSpec>CredentialSpecsCredentialSpec[]CredentialSpecs*[]CredentialSpec= No credential specs.#We recommend that you use this parameter instead of the dockerSecurityOptions.
Currently, only one credential spec is allowed per container definition.
disableNetworkingbooleandisable_networkingbooldisableNetworkingBooleanDisableNetworkingboolDisableNetworking*bool= false#When this parameter is true, networking is disabled within the container.
dnsSearchDomainsstring[]dns_search_domainstyping.List[str]dnsSearchDomainsList<String>DnsSearchDomainsstring[]DnsSearchDomains*[]*string= No search domains.#dnsServersstring[]dns_serverstyping.List[str]dnsServersList<String>DnsServersstring[]DnsServers*[]*string= Default DNS servers.#dockerLabels{ [key: string]: string }docker_labelstyping.Mapping[str, str]dockerLabelsMap<String, String>DockerLabelsIDictionary<string, string>DockerLabels*map[string]*string= No labels.#dockerSecurityOptionsstring[]docker_security_optionstyping.List[str]dockerSecurityOptionsList<String>DockerSecurityOptionsstring[]DockerSecurityOptions*[]*string= No security labels.#enableRestartPolicybooleanenable_restart_policyboolenableRestartPolicyBooleanEnableRestartPolicyboolEnableRestartPolicy*bool= false unless `restartIgnoredExit…#When you set up a restart policy, Amazon ECS can restart the container without needing to replace the task.
default
Default: false unless restartIgnoredExitCodes or restartAttemptPeriod is set.
entryPointstring[]entry_pointtyping.List[str]entryPointList<String>EntryPointstring[]EntryPoint*[]*string= Entry point configured in contai…#default
Default: Entry point configured in container.
environment{ [key: string]: string }environmenttyping.Mapping[str, str]environmentMap<String, String>EnvironmentIDictionary<string, string>Environment*map[string]*string= No environment variables.#environmentFilesEnvironmentFile[]environment_filestyping.List[EnvironmentFile]environmentFilesList<EnvironmentFile>EnvironmentFilesEnvironmentFile[]EnvironmentFiles*[]EnvironmentFile= No environment files.#notes
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 }extra_hoststyping.Mapping[str, str]extraHostsMap<String, String>ExtraHostsIDictionary<string, string>ExtraHosts*map[string]*string= No extra hosts.#healthCheckHealthCheckhealth_checkHealthCheckhealthCheckHealthCheckHealthCheckHealthCheckHealthCheckHealthCheck= Health check configuration from …#default
Default: Health check configuration from container.
imageContainerImageimageContainerImageimageContainerImageImageContainerImageImageContainerImagerequired#notes
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
inferenceAcceleratorResourcesstring[]inference_accelerator_resourcestyping.List[str]inferenceAcceleratorResourcesList<String>InferenceAcceleratorResourcesstring[]InferenceAcceleratorResources*[]*string= No inference accelerators assign…#default
Default: No inference accelerators assigned.
linuxParametersLinuxParameterslinux_parametersLinuxParameterslinuxParametersLinuxParametersLinuxParametersLinuxParametersLinuxParametersLinuxParameters= No Linux parameters.#For more information see KernelCapabilities.
loggingLogDriverloggingLogDriverloggingLogDriverLoggingLogDriverLoggingLogDriver= Containers use the same logging …#default
Default: Containers use the same logging driver that the Docker daemon uses.
memoryLimitMiBnumbermemory_limit_mi_bint | floatmemoryLimitMiBNumberMemoryLimitMiBdoubleMemoryLimitMiB*float64= 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.
memoryReservationMiBnumbermemory_reservation_mi_bint | floatmemoryReservationMiBNumberMemoryReservationMiBdoubleMemoryReservationMiB*float64= No memory reserved.#notes
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.
portMappingsPortMapping[]port_mappingstyping.List[PortMapping]portMappingsList<PortMapping>PortMappingsPortMapping[]PortMappings*[]PortMapping= No ports are mapped.#When this parameter is true, the container is given elevated privileges on the host container instance (similar to the root user).
pseudoTerminalbooleanpseudo_terminalboolpseudoTerminalBooleanPseudoTerminalboolPseudoTerminal*bool= false#This parameter maps to Tty in the "Create a container section" of the Docker Remote API and the --tty option to docker run.
readonlyRootFilesystembooleanreadonly_root_filesystemboolreadonlyRootFilesystemBooleanReadonlyRootFilesystemboolReadonlyRootFilesystem*bool= false#restartAttemptPeriodDurationrestart_attempt_periodDurationrestartAttemptPeriodDurationRestartAttemptPeriodDurationRestartAttemptPeriodDuration= Duration.seconds(300) if `enable…#notes · default
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.
restartIgnoredExitCodesnumber[]restart_ignored_exit_codestyping.List[int | float]restartIgnoredExitCodesList<Number>RestartIgnoredExitCodesdouble[]RestartIgnoredExitCodes*[]*float64= 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 }secretstyping.Mapping[str, Secret]secretsMap<String, Secret>SecretsIDictionary<string, Secret>Secrets*map[string]Secret= No secret environment variables.#startTimeoutDurationstart_timeoutDurationstartTimeoutDurationStartTimeoutDurationStartTimeoutDuration= none#stopTimeoutDurationstop_timeoutDurationstopTimeoutDurationStopTimeoutDurationStopTimeoutDuration= none#systemControlsSystemControl[]system_controlstyping.List[SystemControl]systemControlsList<SystemControl>SystemControlsSystemControl[]SystemControls*[]SystemControl= No system controls are set.#taskDefinitionTaskDefinitiontask_definitionTaskDefinitiontaskDefinitionTaskDefinitionTaskDefinitionTaskDefinitionTaskDefinitionTaskDefinitionrequired#[disable-awslint:ref-via-interface]
This parameter maps to User in the Create a container section of the Docker Remote API and the --user option to docker run.
versionConsistencyVersionConsistencyversion_consistencyVersionConsistencyversionConsistencyVersionConsistencyVersionConsistencyVersionConsistencyVersionConsistencyVersionConsistency= VersionConsistency.DISABLED if `…#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.
default
Default: VersionConsistency.DISABLED if image is a CDK asset, VersionConsistency.ENABLED otherwise
workingDirectorystringworking_directorystrworkingDirectoryStringWorkingDirectorystringWorkingDirectory*string= /#Properties
CONTAINER_PORT_USE_RANGEnumbercontainer_port_use_rangeint | floatCONTAINER_PORT_USE_RANGENumberCONTAINER_PORT_USE_RANGEdoubleCONTAINER_PORT_USE_RANGE*float64requiredstatic#containerDependenciesContainerDependency[]container_dependenciestyping.List[ContainerDependency]containerDependenciesList<ContainerDependency>ContainerDependenciesContainerDependency[]ContainerDependencies*[]ContainerDependencyrequired#containerNamestringcontainer_namestrcontainerNameStringContainerNamestringContainerName*stringrequired#containerPortnumbercontainer_portint | floatcontainerPortNumberContainerPortdoubleContainerPort*float64required#credentialSpecsCredentialSpecConfig[]credential_specstyping.List[CredentialSpecConfig]credentialSpecsList<CredentialSpecConfig>CredentialSpecsCredentialSpecConfig[]CredentialSpecs*[]CredentialSpecConfig#environmentFilesEnvironmentFileConfig[]environment_filestyping.List[EnvironmentFileConfig]environmentFilesList<EnvironmentFileConfig>EnvironmentFilesEnvironmentFileConfig[]EnvironmentFiles*[]EnvironmentFileConfig#notes
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.
ingressPortnumberingress_portint | floatingressPortNumberIngressPortdoubleIngressPort*float64required#This property is only used for tasks that use the awsvpc network mode.
linuxParametersLinuxParameterslinux_parametersLinuxParameterslinuxParametersLinuxParametersLinuxParametersLinuxParametersLinuxParametersLinuxParameters#logDriverConfigLogDriverConfiglog_driver_configLogDriverConfiglogDriverConfigLogDriverConfigLogDriverConfigLogDriverConfigLogDriverConfigLogDriverConfig#memoryLimitSpecifiedbooleanmemory_limit_specifiedboolmemoryLimitSpecifiedBooleanMemoryLimitSpecifiedboolMemoryLimitSpecified*boolrequired#mountPointsMountPoint[]mount_pointstyping.List[MountPoint]mountPointsList<MountPoint>MountPointsMountPoint[]MountPoints*[]MountPointrequired#portMappingsPortMapping[]port_mappingstyping.List[PortMapping]portMappingsList<PortMapping>PortMappingsPortMapping[]PortMappings*[]PortMappingrequired#Port mappings allow containers to access ports on the host container instance to send or receive traffic.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#referencesSecretJsonFieldbooleanreferences_secret_json_fieldboolreferencesSecretJsonFieldBooleanReferencesSecretJsonFieldboolReferencesSecretJsonField*bool#taskDefinitionTaskDefinitiontask_definitionTaskDefinitiontaskDefinitionTaskDefinitionTaskDefinitionTaskDefinitionTaskDefinitionTaskDefinitionrequired#ulimitsUlimit[]ulimitstyping.List[Ulimit]ulimitsList<Ulimit>UlimitsUlimit[]Ulimits*[]Ulimitrequired#volumesFromVolumeFrom[]volumes_fromtyping.List[VolumeFrom]volumesFromList<VolumeFrom>VolumesFromVolumeFrom[]VolumesFrom*[]VolumeFromrequired#Methods
addContainerDependencies(...containerDependencies: ContainerDependency[]): voiddef add_container_dependencies(self, container_dependencies: ContainerDependency) -> Nonepublic void addContainerDependencies(ContainerDependency containerDependencies)public void AddContainerDependencies(ContainerDependency containerDependencies)func AddContainerDependencies(ContainerDependencies ContainerDependency)#addDockerLabel(name: string, value: string): voiddef add_docker_label(self, name: str, value: str) -> Nonepublic void addDockerLabel(String name, String value)public void AddDockerLabel(string name, string value)func AddDockerLabel(Name *string, Value *string)#addEnvironment(name: string, value: string): voiddef add_environment(self, name: str, value: str) -> Nonepublic void addEnvironment(String name, String value)public void AddEnvironment(string name, string value)func AddEnvironment(Name *string, Value *string)#addInferenceAcceleratorResource(...inferenceAcceleratorResources: string[]): voiddef add_inference_accelerator_resource(self, inference_accelerator_resources: str) -> Nonepublic void addInferenceAcceleratorResource(String inferenceAcceleratorResources)public void AddInferenceAcceleratorResource(string inferenceAcceleratorResources)func AddInferenceAcceleratorResource(InferenceAcceleratorResources *string)#addLink(container: ContainerDefinition, alias?: string): voiddef add_link(self, container: ContainerDefinition, alias: typing.Optional[str] = None) -> Nonepublic void addLink(ContainerDefinition container, String alias)public void AddLink(ContainerDefinition container, string? alias = null)func AddLink(Container ContainerDefinition, Alias *string)#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[]): voiddef add_mount_points(self, mount_points: MountPoint) -> Nonepublic void addMountPoints(MountPoint mountPoints)public void AddMountPoints(MountPoint mountPoints)func AddMountPoints(MountPoints MountPoint)#addPortMappings(...portMappings: PortMapping[]): voiddef add_port_mappings(self, port_mappings: PortMapping) -> Nonepublic void addPortMappings(PortMapping portMappings)public void AddPortMappings(PortMapping portMappings)func AddPortMappings(PortMappings PortMapping)#addScratch(scratch: ScratchSpace): voiddef add_scratch(self, scratch: ScratchSpace) -> Nonepublic void addScratch(ScratchSpace scratch)public void AddScratch(ScratchSpace scratch)func AddScratch(Scratch ScratchSpace)#This adds the correct container mountPoint and task definition volume.
addSecret(name: string, secret: Secret): voiddef add_secret(self, name: str, secret: Secret) -> Nonepublic void addSecret(String name, Secret secret)public void AddSecret(string name, Secret secret)func AddSecret(Name *string, Secret Secret)#addToExecutionPolicy(statement: PolicyStatement): voiddef add_to_execution_policy(self, statement: PolicyStatement) -> Nonepublic void addToExecutionPolicy(PolicyStatement statement)public void AddToExecutionPolicy(PolicyStatement statement)func AddToExecutionPolicy(Statement PolicyStatement)#addUlimits(...ulimits: Ulimit[]): voiddef add_ulimits(self, ulimits: Ulimit) -> Nonepublic void addUlimits(Ulimit ulimits)public void AddUlimits(Ulimit ulimits)func AddUlimits(Ulimits Ulimit)#addVolumesFrom(...volumesFrom: VolumeFrom[]): voiddef add_volumes_from(self, volumes_from: VolumeFrom) -> Nonepublic void addVolumesFrom(VolumeFrom volumesFrom)public void AddVolumesFrom(VolumeFrom volumesFrom)func AddVolumesFrom(VolumesFrom VolumeFrom)#findPortMapping(containerPort: number, protocol: Protocol): PortMappingdef find_port_mapping(self, container_port: int | float, protocol: Protocol) -> PortMappingpublic PortMapping findPortMapping(Number containerPort, Protocol protocol)public PortMapping FindPortMapping(double containerPort, Protocol protocol)func FindPortMapping(ContainerPort *float64, Protocol Protocol) PortMapping#findPortMappingByName(name: string): PortMappingdef find_port_mapping_by_name(self, name: str) -> PortMappingpublic PortMapping findPortMappingByName(String name)public PortMapping FindPortMappingByName(string name)func FindPortMappingByName(Name *string) PortMapping#isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#notes · 1 parameter · returns
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
xxxxX— Any object.
Returns: true if x is an object created from a class which extends Construct.
renderContainerDefinition(_taskDefinition?: TaskDefinition): CfnTaskDefinition.ContainerDefinitionPropertydef render_container_definition(self, _task_definition: typing.Optional[TaskDefinition] = None) -> ContainerDefinitionPropertypublic ContainerDefinitionProperty renderContainerDefinition(TaskDefinition _taskDefinition)public ContainerDefinitionProperty RenderContainerDefinition(TaskDefinition? _taskDefinition = null)func RenderContainerDefinition(_taskDefinition TaskDefinition) ContainerDefinitionProperty#1 parameter
Parameters
_taskDefinition_task_definition_taskDefinition_taskDefinition_taskDefinition— [disable-awslint:ref-via-interface] (unused but kept to avoid breaking change).
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#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.
1 parameter · returns
Parameters
mixinsmixinsmixinsmixinsMixins— The mixins to apply.
Returns: This construct for chaining