How to Deploy an Application to AWS Fargate

Agus Richard
Level Up Coding
Published in
10 min readJan 27, 2022

--

Following a step by step process of deploying an application to AWS Fargate with Elastic Container Service and Application Load Balancer.

Photo by Ágatha Depiné on Unsplash

Managing application servers can become a tedious task. You need to patch, provision, configure and scale clusters of virtual machines to run containers. Then there is one jargon you’ve likely heard a lot, that is serverless.

A bit definition about serverless:

Serverless is a cloud-native development model that allows developers to build and run applications without having to manage servers.

When we said serverless, it doesn’t mean that there is no server. It means that the servers are abstracted from application development. All tasks like configuring, maintaining, provisioning, patching and scaling infrastructure are handled by the cloud provider.

There are several advantages regarding serverless:

  • Lower cost
  • Fewer things to worry about
  • Enhanced scalability
  • More focus on user experience

By having these advantages, it doesn't mean that serverless computing is a silver bullet to all applications. There are also cons to using serverless computing when it seems a dedicated server is way better. For example, if you have an application that running for a longer period and doing heavy computing tasks, it would be better to use a dedicated server. Because with serverless, there is a good chance that you’ll pay bigger than you expected.

With all that being said, let’s jump directly to step by step guide for deploying an application to AWS Fargate.

Prerequisites

To follow along with this article, you need an AWS account. It’s okay if you are using the free tier. We’ll clean up our services at the end of this article, so you won’t get billed.

Also, make sure that you have a Docker engine installed on your local machine. We’ll push the docker image to ECR and deploy it to AWS Fargate with ECS.

Note that you can use Fargate with ECS or EKS. But in this article, we’ll focus on utilizing ECS.

To push an image to a private ECR repository, you have to configure your AWS CLI. You can skip to the next section if you’ve configured it.

First, generate an access key. Click your account name on the top left corner of AWS Management Console. Then choose “Security credentials”.

You’ll be redirected to IAM Management Console, then you should click “Create access key”. An access key will be generated and you can download it as a CSV file that contains your access key id and secret access key. Make sure this data is kept confidential.

Now, assume that you have AWS CLI installed. If you haven’t, you can follow this documentation: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html

On your terminal, type aws configure . You’ll be prompted to fill in access key id, secret access key, default region name, and default output format. If everything is correct, the login process will be successful and you are good to go.

A Simple Code

For demonstration purposes, I chose to write the code using Python FastAPI, because of its easy to setup feature. But it doesn’t really matter in which programming language or library the application is written.

Now, we need to install fastapi and uvicorn. To install them, you can run this command.

pip install fastapi uvicorn

Note: Most likely, you should use a virtual environment so you don’t have a messy global Python environment.

Let’s write a code in main.py file.

Extremely simple! Then generate requirements.txt that contains the application’s dependencies by running command pip freeze > requirements.txt .

It’s time to write the Dockerfile.

By looking at this Dockerfile, we know that our application will run on port 8000. We need this information later on when configuring Application Load Balancer.

Build and Push

Go to ECS page and choose Repositories section.

Click “Create repository” and for simplicity, you should only provide repository name.

View detail the newly created repository and there is a button “View push commands”. As easy as it may sounds, basically you can follow all of those steps. First, you need to retrieve an authentication and authenticate your Docker client to your registry. Then build a Docker image and tag it using the repository’s URL. Lastly, push it to the repository.

There we have it, we have our image stored in AWS ECR.

Deploy to Fargate

Okay, we’re on the main topic of this article now.

Create task definition

Still on the same page as before, navigate to task definitions on ECS. We can specify several configurations into task definitions, such as Docker image to use, CPU and memory for the container, instance type, networking mode, etc.

After you click “Create new task definition”, there are several fields you should provide. Note: What you’re looking at below is the UI of new ECS Console.

  • Provide task definition family name, e.g. fastapi-fargate-task.
  • Container name and image URI (you can see this on ECR Repository previously).
  • Since our application runs on port 8000, we need to set container port to 8000.
  • You can provide environment variables as key-value pairs or from a file.
  • Then click next.

Other fields to fill.

  • Choose AWS Fargate for App Environment.
  • Choose Linux for OS.
  • Choose 1vCPU and 2 GB of memory for task size.
  • If you add more than one container, you can provide task sizes for other containers.
  • For task role, you can leave it empty. But if you need to make API requests to other AWS services, you need to choose ecsTaskExecutionRole.
  • Then review and create.

Create cluster

We’re in luck, to create a cluster there are not many fields to fill. You should provide a cluster name, choose VPC and subnets.

By default, the cluster is configured for AWS Fargate. So let’s leave it as it is.

Load balancer and target group

Let’s move to EC2 console. Here, we need to set up a load balancer and target group. A load balancer will sit in front of our Fargate services and redirect user requests from the public internet to our services.

On EC2 console, look inside the left drawer for “Load Balancing” and choose “Load Balancers”. Then click “Create Load Balancer”.

You’ll see options for load balancer types. Now, choose Application Load Balancer.

For the basic configurations:

  • Provide load balancer name, eg: fastapi-fargate-lb.
  • For scheme, leave internet facing selected.
  • Also, the same thing for IP address type, let IPv4 be selected.

For network mapping:

  • Let’s use our default VPC.
  • For mappings, you can select at least two availability zones. We’ll have to select the same thing when creating ECS cluster services. For this example, you can choose 1a and 1b.

Next, we need to create a security group. Open “Create new security group” in another tab.

Fill in the details about security group name and description, e.g: fastapi-fargate-lb-sg and FastAPI Fargate ALB security group, respectively. Note that LB stands for load balancer and SG stands for security group. Then leave VPC as it is.

For the inbound rules, we need to add a new rule.

  • Click add rule and choose HTTP for type and source Anywhere. By doing this, we allow HTTP internet access to our load balancer from anywhere.
  • Leave outbound rules as it is.
  • Finally, click “Create security group”.

Back to security group. If you click refresh icon, you’ll see the newly created security group. Then choose that.

Now, we need to create target group. Like when we were creating security group, open “Create target group” in another tab.

For the basic configurations:

  • Choose IP address as target type.
  • Provide target group name, e.g. fastapi-fargate.
  • Remember that our application runs on port 8000. It means that we need to choose protocol HTTP and port 8000.
  • Then leave the rest as it is and click next.

After that, there will be a section about register targets. We don’t need to do anything for now. We’ll attach load balancer and target group to Fargate instances when we are creating the cluster’s service.

Back to when we had to choose a target group. Click refresh then you can choose the newly created target group. Then jump to the bottom of the page and click create.

Create Fargate service

After spending several moments in EC2 console, we need to go back to ECS console to create a service inside the previously created ECS cluster. So, choose our cluster.

Note: I switched off the new ECS console UI. When creating a cluster’s service, I think the new look feels a bit wonky. Therefore I chose to use the old one.

After you click create, you’ll see a page like the below image.

  • For Launch type, choose Fargate.
  • For OS family, choose Linux.
  • Previously, we’ve created a task definition and we’ll use it here. Choose that one, including task definition revision.
  • Fill in service name.
  • For number of tasks, this value specifies how many Fargate instances will be created. So the final architecture will be composed of a load balancer and three services.
  • Then choose the next step.

Next, configure network.

  • Choose default VPC.
  • Choose subnets. Make sure that you use the same subnets as in the load balancer.
  • For security groups, click Edit. There will be a left drawer opened.

Here, create a new security group by filling in the security group name. Leave the inbound rules as it is. Then click save.

Now, we need to attach our services to the load balancer.

  • For Load balancer type, choose Application Load Balancer.
  • For load balancer name, choose our load balancer.
  • For container name and port, it seems like you’ve chosen the correct container name and port. But you still need to click “Add to load balancer”.
  • For production listener port, choose port 80.
  • For target name, choose the previously created target group.

You can go to the next step to set up auto scaling. I skip this one, so there are only three services no matter how much load our services handle. Lastly, go to review and create.

Modify service’s security group

To make sure everything works as intended, we need to modify ECS service’s security group to allow load balancer access. Go to service’s security group by clicking security group id.

Edit inbound rules for this security group to allow load balancer access. To do that, choose all TCP access and source to custom. After that, for the source’s value choose load balancer security group like in the below image (or you can copy security group id of the load balancer into this field).

Finally

Okay, this is the last one. I promise!

Back to our load balancer and open the DNS name in the new tab.

Now, you can see “Hello World” on your screen. How interesting is that? :)

Conclusion

Before closing this article, you should clean up the previously created AWS services if you don’t want to get billed. This is the list of things you need to clean up:

  • Stop all cluster’s tasks
  • Delete cluster’s service
  • Delete cluster
  • Delete ECR repository
  • Delete load balancer
  • Delete security group

It’s okay if you want to keep security groups and ECS task definitions. But you can also clean them up.

Okay, I congratulate you if you made it to this last section. There are quite enough steps only to deploy a containerized application. Several times we went back and forth. Set up this, then create that.

It will be such a tedious task if we have to do this thing over and over again. Do you want to do this over and over again? Certainly, I don’t.

Therefore, CI/CD will go hand in hand with this technology. Then infrastructure as code will make it much and much better. We’ll see the continuation in the next articles.

Code for this article: https://github.com/agusrichard/aws-workbook/tree/master/fastapi-fargate

Thank you for reading and happy coding!

--

--

Software Engineer | Data Science Enthusiast | Photographer | Fiction Writer | Freediver LinkedIn: https://www.linkedin.com/in/agus-richard/