Switching from an EC2 instance to ECS

I switched my flask app to Docker, created a container registry, and created an ECS cluster on Fargate.

My flask app running on ECS

To test, call my Amazon Connect phone number: 1-845-318-2265

Github Link

Responsive image

Create a Docker image and push to ECR

First, I needed to switch the app over to Docker, build the image, and push to my new container registry.

Dockerfile:

# syntax=docker/dockerfile:1

FROM python:3.8-slim-buster

WORKDIR /flask

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY . .

CMD [ "python3", "-m" , "application", "run", "--host=0.0.0.0"]

Next, I built the image and made sure it could run locally.

docker build -f Dockerfile.dockerfile --tag flask-phones .

docker run -p 5000:5000 --name flask-app flask-phones

Creating an Elastic Container Registry is straightforward, and I just needed to run the login command from the documentation to connect with the AWS CLI.

Once connected, I pushed my image to my registry with:

docker push accountId.dkr.ecr.us-east-2.amazonaws.com/flask-phones:latest

Create an ECS Cluster and Task Definition

Since my flask application uses Boto3 to fetch data from Cloudwatch, in my task definition I defined two environment variable keys, aws_access_key_id and aws_secret_access_key, and fetched the values from AWS Secrets manager.

I also needed to create a new IAM role and attach it as a Task Role in the Task Definition, in order to allow my app to access Cloudwatch using Boto3, and Secrets Manager to fetch my AWS credentials for Boto3.