Running ECS tasks

We've seen how we can deploy long-running applications as ECS services, but how do we run ad-hoc tasks or short-lived containers using ECS? The answer of course is to create an ECS task, which typically are used to run ad-hoc tasks, such as running a deployment script, performing database migrations, or perhaps performing scheduled batch processing.

Although ECS services are essentially long-running ECS tasks, ECS does treat ECS tasks that you create yourself quite differently from ECS services, as described in the following table:

ECS Services vs ECS Tasks

Let's now see how you run ECS tasks using the AWS console. You will create a very simple ECS task that runs the sleep 300 command from the Nginx image defined in your ECS tasks definition.

This will cause the task to sleep for five minutes before executing, simulating a short-lived ad-hoc task:

  1. In the ECS console, select Clusters on the left and click on your cluster named test-cluster.
  1. Select the Tasks tab and click on the Run new Task button to create a new ECS task:
Running an ECS Task
  1. In the Run Task screen, first select EC2 as the Launch type and ensure that the Task Definition and Cluster settings are configured correctly. If you expand the Advanced Options section, notice that you can specify container overrides for the nginx container. Note that to configure a command override, you must supply the command you want to run along with any arguments in a comma separated format—for example, to execute the sleep 300 command, you must configure a command override of sleep,300. Once configuration is complete, click on Run Task to execute your new ECS task:
Configuring an ECS Task

At this point, you will be returned to the Tasks tab for the ECS cluster and you should see a new task with a state of PENDING:

ECS Task in a Pending State

The new task should quickly transition to a status of RUNNING, and if we left the task to run it would eventually exit after five minutes.

Let's now take this opportunity to observe the behavior of ECS tasks when they are stopped. If you select all tasks and click the Stop button, you will be prompted to confirm you want to stop each task. After confirming you want to stop each task, the Tasks pane should immediately display no active tasks, and after clicking the refresh button a few times, you should see a single task start back up. This task was automatically started by ECS, in order to maintain a desired count of 1 for the simple-web service.