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; andexodus
— 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
.
The details of the task are captured as JSON.
{
"family": "trundler-api",
"cpu": "256",
"memory": "512",
"networkMode": "awsvpc",
"containerDefinitions": [
{
"name": "trundler-api",
"portMappings": [
{
"hostPort": 5000,
"protocol": "tcp",
"containerPort": 5000
}
]
}
]
}
Test
📢 Run this task manually, just to check that it works!
Select the following security groups:
flask
(inbound TCP traffic on port 5000) andexodus
(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.
- Go to the EC2 Console.
- Select Target Groups in the menu bar.
- Press the button.
- Choose IP addresses as the target type.
- Specify a suitable target group name.
- The protocol and port should be HTTP and 80 respectively. This is the protocol and port for incoming requests.
- Press the button.
- 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.