AWS EC2: Creating a Target Group

If we want to have an ECS service which is visible to the public, then we need to set up an Application Load Balancer. There are a couple of steps to this process, the first of which is creating a Target Group.

I’m assuming that we already have an ECS cluster set up.

Create Security Group

This time our example application is different: a Flask API wrapped up in a Docker image and serving requests on port 5000. We want to make this accessible on port 80.

Create the following security groups:

  • flask — inbound TCP traffic on port 5000;
  • http — inbound TCP traffic on port 80; and
  • exodus — outbound traffic on all protocols to all ports and IP addresses.

Task Definition

Create a task definition for the Flask API.

Specify role-task-execution for the task execution role. This is especially important to ensure access to secrets if you’re using a private image.

In the Port mappings section of the container configuration give the port on which the container accepts connections. This assumes that the network mode is awsvpc.

Adding a port mapping to an ECS task definition.

The details of the task are captured as JSON.

The task configuration file below has been abridged and edited for clarity.
  "family": "trundler-api",
  "cpu": "256",
  "memory": "512",
  "networkMode": "awsvpc",
  "containerDefinitions": [
      "name": "trundler-api",
      "portMappings": [
          "hostPort": 5000,
          "protocol": "tcp",
          "containerPort": 5000


📢 Run this task manually, just to check that it works!

Select the following security groups:

  • flask (inbound TCP traffic on port 5000) and
  • exodus (output traffic on all ports; 🚨 vital for accessing Secrets Manager with private images).

If the task doesn’t run as expected then the rest of this procedure is going to be fruitless.

Target Group

Now we’re ready to create the target group.

  1. Go to the EC2 Console.
  2. Select Target Groups in the menu bar.
  3. Press the button.
  4. Choose IP addresses as the target type.
  5. Specify a suitable target group name.
  6. The protocol and port should be HTTP and 80 respectively. This is the protocol and port for incoming requests.
  7. Press the button.
  8. Press the button.

We don’t manually add anything to the target group. It will be automatically populated once we hook it up to the load balancer.

Health Checks

It’s possible to create health checks associated with a target group. These will indicates whether or not the target group is functioning as expected.

You may want to reduce the frequency of the health checks. By default these will be done every 30 seconds.

📢 If the target implements basic HTTP authentication then you’ll need to update the Health Checks and include 401 (Unauthorized) as a success code.