An Amazon ECS task that will run for a specified duration, then be automatically stopped.
Maish Saidel-Keesing
Senior Developer Advocate at AWS
About
In some cases you may wish to limit how long a task can run for. This can be used to prevent a batch job from running too long, or to provide a maximum lifespan for an ephemeral game server or similar server that should boot clients after a period of time.
This pattern will show how to use a sidecar container to trigger Amazon ECS task to stop the task after a duration that you set.
Task Definition
Create a task definition using one of the following methods:
AWSTemplateFormatVersion:'2010-09-09'Description:An example task definition that has a maximum lifespan. Afterthe duration is up, the task automatically stops.Resources:SampleTaskDefinition:Type:AWS::ECS::TaskDefinitionProperties:Family:lifespanCpu:256Memory:512RequiresCompatibilities:- FARGATENetworkMode:awsvpcContainerDefinitions:# The application container- Name:nginxImage:public.ecr.aws/nginx/nginx:mainlineEssential:true# Sidecar container that gives this task a lifetime- Name:lifespanImage:public.ecr.aws/docker/library/busybox:stableCommand:- "sh"- "-c"- "sleep $LIFESPAN_SECONDS"Environment:- Name:LIFESPAN_SECONDSValue:60Essential:true
Deploy the CloudFormation template above by using the AWS CloudFormation web console.
Alternatively you can deploy from the command line with:
You can use the Amazon ECS console to launch a copy of the task as a standalone task. After 60 seconds you should see the task stop with a final message of “Essential container in task exited”
🎓
New Workshop Series!
Join our upcoming container workshop series and learn best practices for Amazon ECS, AWS Fargate, and more.