<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alex Petul on Medium]]></title>
        <description><![CDATA[Stories by Alex Petul on Medium]]></description>
        <link>https://medium.com/@alexpetul?source=rss-31199bbf4405------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zS6nmcKMLvhptSSNGQsrXQ.jpeg</url>
            <title>Stories by Alex Petul on Medium</title>
            <link>https://medium.com/@alexpetul?source=rss-31199bbf4405------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:51:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexpetul/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deploy FastAPI to AWS with ECS]]></title>
            <link>https://medium.com/@alexpetul/deploy-fastapi-to-aws-with-ecs-55493748ca7d?source=rss-31199bbf4405------2</link>
            <guid isPermaLink="false">https://medium.com/p/55493748ca7d</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[deployment-automation]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <dc:creator><![CDATA[Alex Petul]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 15:20:57 GMT</pubDate>
            <atom:updated>2023-04-04T15:20:57.049Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A step by step guide to deploy your FastAPI application to AWS.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*M-uFz7pFU_OMJ_T_RaGWVA.png" /></figure><p>In this article i will show you how to setup a simple Gitlab CI/CD pipeline and deploy dockerized FastAPI application to AWS. You can find a Github link in the end of this article. Let’s move on!</p><h4><strong>Prerequisites</strong></h4><p>First of all it’s assumed that you have an active AWS account and configured AWS CLI on your machine. If not, follow <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">this guide</a> to set it up. For demonstration purposes I’m going to use my root account. However, you should avoid doing this in a development or production environment.</p><p>To automate deployment process we will use Gitlab CI/CD, thus make sure you have an active and registered gitlab-runner.</p><h4><strong>Project overview</strong></h4><p>FastAPI application provides two endpoints for creating and retrieving user data. It can be easily started using docker-compose up. You can clone the project here.</p><pre>version: &quot;3.7&quot;<br><br>services:<br>  web:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    command: sh -c &quot;uvicorn main:app --reload --host 0.0.0.0 --port 8000&quot;<br>    volumes:<br>      - &quot;./app:/app&quot;<br>    ports:<br>      - &quot;8000:8000&quot;<br>    environment:<br>      POSTGRES_NAME: postgres<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: postgres<br>      POSTGRES_HOST: postgres<br>    restart: always<br>    depends_on:<br>      - postgres<br>    networks:<br>      - ig_webapp<br><br>  postgres:<br>    image: postgres:14-alpine<br>    volumes:<br>      - &quot;./.data/postgres:/var/lib/postgresql/data&quot;<br>    environment:<br>      POSTGRES_DB: postgres<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: postgres<br>    networks:<br>      - ig_webapp<br><br>networks:<br>  ig_webapp:</pre><p>You can access swagger page by navigating to<a href="http://localhosts:8000/docs:">localhosts:8000/docs</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1jOLz3ATCOJdAtC-FSgdg.png" /><figcaption>FastAPI application</figcaption></figure><blockquote>Note: In this application I implemented the <a href="https://www.cosmicpython.com/book/chapter_02_repository.html">Repository pattern</a>. It’s absolutely redundant for such a small project, but it can be great fundament to build scalable and maintainable application.</blockquote><h4><strong>AWS environment</strong></h4><p>In this section i will guide you how to set up ECR, ECS, ELB and RDS services.</p><p><strong>Step 1: Create Elastic Load Balancer<br></strong>Since we want to run our FastAPI application with Fargate engine, the public IP address will change every time a new task revision is deployed. It’s not very convenient way to access our service, so let&#39;s take a few minutes and configure a load balancer with a static IP address.</p><blockquote>Note: once the ECS service is created, it’s not possible to assign a load balancer for it. Make sure you did not skip this section if you want a static ip address and DNS name for your application.</blockquote><p>AWS provides two types of load balancers: Application Load Balancer (ALB) and Network Load Balancer (NLB). The main difference between them is that ALB lies on the top of OSI model, while ELB operates at the transport layer (Layer 4). Application load balancer is a good choice for web applications which usually require advanced routing and balancing capabilities. Network load balancer can help you to manage apps which require high-performance, low latency, and scalability such as real-time or IoT applications.</p><p>Navigate to EC2 service, from the sidebar choose Load Balancers and press “Create load balancer”. From the list of LB types choose <strong>Application Load Balancer</strong>. Pick a name and select <strong>Internet-facing</strong> as a scheme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nI6gjkWJLAhDVEBDtoDVTw.png" /></figure><p>In the networking section, as AWS recommends, select two availability zones (for eg. <em>us-east-1a</em> and <em>us-east-1b</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0WCx6exknymp1URU_eH7w.png" /><figcaption>AWS ELB — Network mapping</figcaption></figure><p>In the listeners and routing section add a new listener with HTTP protocol, which will accept traffic on the port 80. To register default action press “Create target group” and do not close current tab in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLjj6D9bYTUfAEwTx8JS3Q.png" /><figcaption>AWS ELB — Listeners and routing</figcaption></figure><p>Target groups define rules on how to route incoming traffic: EC2 instances, fixed IP addresses, AWS Lambda functions, etc. Select IP address type and tell target group to accept traffic on port 80.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2BI5P71Oq8nBN4ORUhH_Q.png" /><figcaption>AWS ELB — Target group configuration</figcaption></figure><p>On the next step, you can manually specify ip address from the selected network. <em>I recommend adding one record for each subnet declared on the load balancer to avoid the known problem of “Task failed ELB health checks”</em>. Click the “Create target group” button and create a load balancer with the newly added target group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_CjfHrBxf3cFr3WSlqGpw.png" /><figcaption>AWS ELB — Target group network configuration</figcaption></figure><p><strong>Step 2: Create PostgreSQL RDS<br></strong>Navigate to the RDS service and press the “Create database” button. While you can configure all options manually, in this tutorial we will stick to easy create method. Make sure you select a free tier instance size and fill all the required fields. With this instance size you may experience minor performance issues, but it should be sufficient to test some simple I/O operations. Click the “Create database” and wait a few minutes for it to spin up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hItTOnX8ZElHcYiuvjnnhg.png" /><figcaption>AWS RDS configuration</figcaption></figure><p><strong>Step 3: Create Elastic Container Registry</strong><br>Navigate to Elastic Container Registry service and press the “Create repository” button. You can fill all the settings with default values, but make sure the registry is private, since we don’t want anyone to access it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*prZVgbHF7_1frKFgnRZX8w.png" /><figcaption>AWS ECR — Private repository</figcaption></figure><p><strong>Step 4: Create task definition<br></strong>Task definition is a blueprint that defines how Docker container should run within an ECS. It specifies which image to use, how much memory and CPU to allocate, which ports to map and other container settings such as environment variables. Once a task definition is created, it can be used to launch one or more tasks on the ECS cluster.</p><p>Navigate to ECS service and select “Create new task definition”. Here are the key settings that should be specified:</p><ol><li><em>Image URI</em> — Docker image which is stored in the newly created ECR. Since the repository does not have any images, just copy and paste its URI without specifying any tags, we will come back to it later.<br>For eg. 353586219743.dkr.ecr.us-east-1.amazonaws.com/fastapi-demo</li><li><em>Container port</em> — define the port number, which should be exposed for Docker container. In out case it’s 8000.</li><li><em>Environment variables</em> — paste database url of the newly created PostgreSQL database. For example:</li></ol><pre>DATABASE_URL=postgresql+asyncpg://postgres:postgres@fastapi-demo-database.c3vsmh6klo8j.us-east-1.rds.amazonaws.com:5432/postgres</pre><p>For the next steps feel free to leave all the default values. Make sure you set <strong>AWS Fargate (serverless)</strong> as an app environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BU83vCxb4PCyrrZ3MlMIuw.png" /><figcaption>AWS ECS — Task definition</figcaption></figure><p><strong>Step 5: Create Elastic Container Service<br></strong>Navigate to Elastic Container Service and press “Create cluster”. Enter the desired name of the cluster and leave the networking section as is. In the infrastructure section select <strong>AWS Fargate (serverless) </strong>and create a cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1iUK5EeUKTHdvJuvCX1p9A.png" /><figcaption>AWS ECS — Cluster configuration</figcaption></figure><p>Our cluster is set up and now it’s time to add services!</p><p>Navigate to the newly created ECS cluster and under services section press “Create”. You will be asked to set up compute options. We are going to stick to <strong>Fargate</strong> launch type. It’s a launch type, where all the provisioning and managing of underlying infrastructure is done by AWS. EC2 launch type can bring you more flexibility, however it requires some additional configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDBG4AC_Gz8DiG_MsyRS0g.png" /><figcaption>AWS ECS — Compute configuration</figcaption></figure><p>In the deployment configuration section you need to specify how and what ECS cluster is going to launch. There are two main application types:</p><ol><li><em>Service</em> — enables you to run and maintain the desired number of instances of a Task definition. Think about this as a constantly running process that can be stopped and restarted.</li><li><em>Task</em> — allows you to run and terminate a specific task. For example, it can be a task, which is running migrations to a database or collecting static files to S3.</li></ol><p>Select recently created Task definition family, pick a name for your service and set the desired number of tasks to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*po9wX_Wro5RAoBx6EuXjTQ.png" /><figcaption>AWS ECS — Deployment configuration</figcaption></figure><p>In the Networking section you can leave all the settings by default. Make sure you specified at least one subnet and security group.</p><blockquote>Note: If Public IP is turned on, your service will be assigned a public IP, which will be reassigned every time a new deployment is rolled out.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNJ8vFyliqhnvbp3M2SBBw.png" /><figcaption>AWS ECS — Networking</figcaption></figure><p>If you want your service to be accessed through a load balancer, fill the fields with values from <em>step 1</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cVipr6MJofbtNXNpuhaCQ.png" /><figcaption>AWS ECS — Load balancer</figcaption></figure><p>After creating service, a new deployment task will be started. However, it is going to fail, because the image we specified in the Task definition does not actually exist in ECR. Let’s fix it and automate deployment process!</p><h4><strong>Step 6: Setup Gitlab CI/CD</strong></h4><p>Continuous integration and deployment processes usually include building, testing and deploying itself. In this article we are going to skip testing stage. Below you can see .gitlab-ci.yml :</p><pre>image: docker:latest<br><br>services:<br>  - docker:dind<br><br>stages:<br>  - build<br>  - deploy<br><br>build_push:<br>  stage: build<br>  script:<br>    - sh ./ci.sh<br>  only:<br>    - master<br><br>deploy:<br>  stage: deploy<br>  script:<br>    - make aws-deploy<br>  only:<br>    - master</pre><p>Once the master branch is updated, continuous integration process starts. It automatically authenticates you with AWS credentials, builds and pushes image to remote ECR host. Below you can see ci.sh file:</p><pre>#!/bin/bash<br><br>set -e<br><br>AWS_ECR_HOST=&quot;353586219743.dkr.ecr.us-east-1.amazonaws.com&quot;<br>AWS_REGION=&quot;us-east-1&quot;<br>AWS_IMAGE_NAME=&quot;fastapi-demo&quot;<br><br>function ecr_login () {<br>  aws_version=$(aws --version)<br>  if [[ $aws_version == *&quot;aws-cli/2&quot;* ]]<br>  then<br>      aws ecr get-login-password --region &quot;$AWS_REGION&quot; | docker login --username AWS --password-stdin &quot;$AWS_ECR_HOST&quot;<br>  elif [[ $aws_version == *&quot;aws-cli/1&quot;* ]]<br>  then<br>      $(aws ecr get-login --no-include-email --region &quot;$AWS_REGION&quot;)<br>  else<br>      kill -INT $$<br>  fi<br>}<br><br>function build_push () {<br>  # Create image with tag, based on current git commit<br>  backend_image=&quot;${AWS_ECR_HOST}/${AWS_IMAGE_NAME}:$CI_COMMIT_REF_NAME.$CI_COMMIT_SHORT_SHA&quot;<br><br>  # Build image<br>  docker build -t &quot;$backend_image&quot; .<br><br>  # Push image to ECR<br>  docker push &quot;$backend_image&quot;<br>}<br><br>ecr_login<br>build_push</pre><p>Now it’s time for the most tricky part. Let’s take a look at how make aws-deploy command works. Here you can see Makefile:</p><pre>ECS_CLUSTER = fastapi-demo-cluster<br>ECS_SERVICE = fastapi-demo-main-service<br>ECS_TASK_DEFINITION = fastapi-demo-task-definition-family<br>ECR_HOST = 353586219743.dkr.ecr.us-east-1.amazonaws.com<br><br>IMAGE_NAME = fastapi-demo<br><br>APP_VERSION ?= master.$(shell git rev-parse --short=8 HEAD)<br><br>DATA_ROOT_DIR ?= $(CURDIR)<br><br>aws-alembic-migrate:<br> @ aws ecs run-task \<br>  --cluster $(ECS_CLUSTER) \<br>  --task-definition $(ECS_TASK_DEFINITION):$(shell cat $(DATA_ROOT_DIR)/$(ECS_TASK_DEFINITION).rev) \<br>  --count 1 \<br>  --launch-type FARGATE \<br>  --network-configuration &quot;awsvpcConfiguration={subnets=[subnet-0d2b2f554fb0a3013,subnet-0733a5d6e186fa913],securityGroups=[sg-04404962fa02f3fb4],assignPublicIp=ENABLED}&quot; \<br>  --overrides &#39;{&quot;containerOverrides&quot;: [{&quot;name&quot;: &quot;$(IMAGE_NAME)&quot;, &quot;command&quot;: [&quot;alembic&quot;, &quot;upgrade&quot;, &quot;head&quot;]}]}&#39;<br><br>aws-update-service:<br> @ aws ecs update-service \<br>  --cluster $(ECS_CLUSTER) \<br>  --service $(ECS_SERVICE) \<br>  --desired-count 1 \<br>  --task-definition $(ECS_TASK_DEFINITION):$(shell cat $(DATA_ROOT_DIR)/$(ECS_TASK_DEFINITION).rev)<br><br>aws-perform-update-task-definition:<br> @ aws ecs describe-task-definition \<br>   --task-definition &quot;$(ECS_TASK_DEFINITION)&quot; | jq &#39;.taskDefinition | .containerDefinitions[0].image = &quot;$(ECR_IMAGE)&quot; | del(.taskDefinitionArn) | del(.revision) | del(.status) | del(.requiresAttributes) | del(.compatibilities) | del(.registeredAt) | del(.registeredBy)&#39; &gt; $(DATA_ROOT_DIR)/$(ECS_TASK_DEFINITION).json<br><br> @ aws ecs register-task-definition \<br>   --cli-input-json file://$(DATA_ROOT_DIR)/$(ECS_TASK_DEFINITION).json | jq &#39;.taskDefinition.revision&#39; &gt; $(DATA_ROOT_DIR)/$(ECS_TASK_DEFINITION).rev<br><br>aws-update-task-definition:<br> @ ECR_IMAGE=&quot;$(ECR_HOST)/$(IMAGE_NAME):$(APP_VERSION)&quot; TASK_DEFINITION=&quot;$(ECS_TASK_DEFINITION)&quot; make aws-perform-update-task-definition<br><br>aws-clean:<br> @ rm -rf $(DATA_ROOT_DIR)/*.json $(DATA_ROOT_DIR)/*.rev<br><br>aws-deploy: aws-update-task-definition aws-alembic-migrate aws-update-service aws-clean</pre><p>On the first step it reads a Task definition and replaces a Docker image with newly created image in ECR. Based on the generated json configuration a new Task revision is created by calling CLI command aws ecs register-task-definition.</p><p>After the Task definition is updated, we call CLI command aws ecs run-taskto apply migrations to a database. Since the default Docker container command is used to launch FastAPI application, we need to specify migration command directly:</p><pre>{&quot;containerOverrides&quot;: [{&quot;name&quot;: &quot;$(IMAGE_NAME)&quot;, &quot;command&quot;: [&quot;alembic&quot;, &quot;upgrade&quot;, &quot;head&quot;]}]}</pre><blockquote>Note: When running Fargate tasks in AWS, specifying an awsvpcConfiguration is necessary because it defines the networking mode for the task.The awsvpc networking mode provides each task with its own unique network namespace, which means that each task gets its own unique network interface and IP address Make sure you specified subnets and security groups correctly.</blockquote><p>Finally, we need to update ECS service to use a newly created Task revision by calling CLI command aws ecs update-service. A new deployment process will be started.</p><h4><strong>Bringing everything together</strong></h4><p>Now clone the repository from <a href="https://github.com/AlexPetul/fastapi-demo-ecs">here</a>. Make sure all the variables in ci.sh and Makefile are set according to your AWS environment. Push your code to the GitLab repository and wait for the pipeline to succeed.</p><p>Once the deployment process has finished, navigate to a running task within ECS service. You should see that public IP address has been assigned for it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Gn0fuTNH6W1zfF6FaeG8w.png" /><figcaption>AWS ECS — Task’s public IP</figcaption></figure><p>If you copy that address and try to access swagger page using port 8000, you will see the swagger page. You can also access it with load balancer DNS name without specifying the port:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Khggv0Jq2rjmZx3M24-9zQ.png" /><figcaption><a href="http://fastapi-demo-lb-2056025675.us-east-1.elb.amazonaws.com/docs">http://fastapi-demo-lb-2056025675.us-east-1.elb.amazonaws.com/docs</a></figcaption></figure><h4><strong>Congratulations!</strong></h4><p>If you got this far, you have a lot of patience and dedication. You did not just deployed FastAPI application, but also learnt a lot of good staff.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55493748ca7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>