From Code to Production: Building an Automated CI/CD Pipeline with GitHub Actions, Docker and AWS EC2

A hands-on DevOps project: Containerizing a FastAPI application, automating Docker image builds, deploying to AWS EC2, and implementing health checks with rollback handling.
Introduction
When I started learning DevOps, I understood individual tools such as Git, Docker, GitHub Actions and AWS. However, I wanted to understand something more important: how do these tools work together to deliver an application?
What happens after a developer pushes code to GitHub? How does that code become a Docker image? How does the image reach a server? And how do we know whether the newly deployed application is actually working?
This project demonstrates an automated FastAPI CI/CD pipeline using GitHub Actions, Docker, Docker Hub and AWS EC2. A push to main triggers image building and publishing, followed by SSH-based deployment. On EC2, a Bash script health-checks a candidate container before promotion and attempts rollback if production verification fails. Promotion can cause a brief interruption; this is not a zero-downtime deployment.
To understand this complete process, I built an end-to-end project called FastAPI Docker Pipeline.
The objective was to automate the application build, containerization, image publishing and deployment process using GitHub Actions, Docker, Docker Hub and AWS EC2.
I also implemented a candidate-based deployment approach with health verification and rollback handling to understand how deployment failures can be managed.
In this article, I'll explain how I built the project, why I selected these technologies, how the CI/CD pipeline works and what happens behind the scenes during deployment.
Let's get started!
1. What Are We Building?
The project automates the deployment of a simple FastAPI application to an AWS EC2 instance.
Whenever a new commit is pushed to the main branch of the GitHub repository:
- GitHub Actions automatically starts the workflow.
- Docker builds an image of the FastAPI application.
- The image is tagged with
latestand the Git commit SHA. - Both image tags are pushed to Docker Hub.
- GitHub Actions connects to the EC2 instance through SSH.
- The deployment script is transferred and executed.
- The EC2 instance pulls the new Docker image.
- A candidate container is started and health-checked.
- If the candidate is healthy, it is promoted to the production application.
- The deployment script verifies the production application and can restore the previous container if verification fails.
The main objective is to eliminate repetitive manual deployment steps and understand the complete CI/CD lifecycle.
GitHub repository: https://github.com/madhucheran/fastapi-docker-pipeline
2. Which Technologies Are Used?
Before looking at the implementation, let's understand the technologies used in this project.
| Technology | Purpose |
|---|---|
| Python | Programming language |
| FastAPI | Backend application framework |
| Docker | Containerization |
| Docker Hub | Container image registry |
| GitHub | Source code management |
| GitHub Actions | CI/CD automation |
| AWS EC2 | Application hosting |
| Ubuntu Linux | EC2 server operating system |
| SSH | Secure remote server connection |
| Bash | Deployment automation |
Each technology has a different responsibility.
For example, GitHub stores the source code, GitHub Actions automates the pipeline, Docker packages the application, Docker Hub stores the image, and EC2 runs the application.
Understanding these responsibilities makes the entire architecture easier to follow.
3. How Does the CI/CD Architecture Work?
Before jumping into the code, I wanted to understand how all the components communicate.
The project has two major stages:
Continuous Integration (CI)
This stage is responsible for building the Docker image and publishing it to Docker Hub.
Continuous Deployment (CD)
This stage connects to the EC2 instance, retrieves the deployment script, pulls the required image and manages the deployment.
Here is the architecture of the project:
The most important thing to understand here is that CI and CD are connected but perform different responsibilities.
CI produces the application image. CD takes that image and deploys it to the server.
4. How Is the Project Structured?
I organized the repository into application code, Docker configuration, GitHub Actions workflow and deployment automation.
fastapi-docker-pipeline/
│
├── .github/
│ └── workflows/
│ └── docker-build.yml
│
├── scripts/
│ └── deploy.sh
│
├── main.py
├── requirements.txt
├── Dockerfile
├── .dockerignore
├── .gitignore
└── README.md
Let's understand the purpose of each important file.
| File | Responsibility |
|---|---|
main.py |
FastAPI application |
requirements.txt |
Python dependencies |
Dockerfile |
Docker image instructions |
.dockerignore |
Excludes unnecessary files from Docker build context |
docker-build.yml |
GitHub Actions CI/CD workflow |
deploy.sh |
EC2 deployment, health verification and rollback |
I kept the deployment logic in a separate Bash script rather than putting all the commands directly inside the GitHub Actions workflow.
This makes the deployment process easier to manage and understand.
5. How Do We Build the FastAPI Application?
For this project, I used FastAPI to create a small backend application.
I intentionally kept the application simple because my main objective was to understand the DevOps workflow rather than build a complex application.
The application is defined in main.py.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello Cloud"}
@app.get("/health")
def health_check():
return {"status": "healthy"}
There are two endpoints.
1. Root endpoint – /
When someone accesses the root endpoint, the application returns:
{
"message": "Hello Cloud"
}
2. Health endpoint – /health
The health endpoint returns:
{
"status": "healthy"
}
Why did I create a separate health endpoint?
Because a running application process does not necessarily mean that the application is functioning correctly.
A health endpoint provides a simple way to check whether the application is responding to HTTP requests.
Later in the project, I use this endpoint as part of the Docker health check and deployment verification process.
6. Which Python Dependencies Does the Application Need?
The project uses a requirements.txt file to define the Python dependencies.
Some of the important packages are:
fastapi– The web framework.uvicorn– The ASGI server that runs the application.pydantic– Data validation functionality used by FastAPI.starlette– The underlying ASGI toolkit used by FastAPI.
The dependencies are pinned to specific versions.
For example:
fastapi==0.141.1
uvicorn==0.53.0
pydantic==2.13.5
starlette==1.6.0
Pinning package versions helps maintain more consistent dependency installations across environments.
7. How Do We Containerize the Application with Docker?
After creating the FastAPI application, the next step was to containerize it.
Why Docker?
Without containerization, we would need to configure the Python environment, install dependencies and manage the runtime environment separately on the deployment server.
Docker allows us to package the application and its dependencies into an image.
I created a Dockerfile containing the following instructions:
FROM python:3.11-slim
WORKDIR /app
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
HEALTHCHECK --interval=5s --timeout=30s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Let's understand each instruction.
FROM python:3.11-slim
This selects the Python 3.11 slim image as the base image.
Instead of configuring Python manually, Docker starts with an image that already contains Python.
The slim variant provides a smaller base environment than the full Python image.
WORKDIR /app
This sets /app as the working directory inside the container.
Subsequent commands execute relative to this directory.
Installing curl
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
I installed curl because the Docker health check uses it to send an HTTP request to the application's health endpoint.
The package manager's downloaded package-list files are removed afterward to avoid retaining unnecessary data in the image layer.
COPY requirements.txt .
This copies the dependency file into the container.
Notice that I copy requirements.txt separately before copying the entire application.
Installing dependencies
RUN pip install --no-cache-dir -r requirements.txt
This installs all the Python dependencies required by the application.
Using --no-cache-dir prevents pip from retaining its downloaded package cache.
COPY . .
This copies the remaining application files into the container's working directory.
EXPOSE 8000
This documents that the application listens on port 8000 inside the container.
It does not independently publish the port to the host. Port publishing is configured later through docker run.
HEALTHCHECK
HEALTHCHECK --interval=5s --timeout=30s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
This is an important part of the project.
Docker periodically checks the application's health by sending a request to /health.
--interval=5s: Runs the check every five seconds.--timeout=30s: Allows up to 30 seconds for a check to complete.--start-period=5s: Allows the application an initial startup period.--retries=3: Three consecutive failed checks can mark the container unhealthy.
When the health endpoint responds successfully, Docker reports the container as healthy.
CMD
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
This starts the FastAPI application using Uvicorn.
Here:
mainrefers tomain.py.apprefers to the FastAPI instance.0.0.0.0allows the application to listen on the container's network interfaces.8000is the application port.
At this point, our application is ready to run inside a Docker container.
8. Why Use a .dockerignore File?
I also created a .dockerignore file.
venv/
.venv/
__pycache__/
*.pyc
.git/
Why is this useful?
When Docker builds an image, it uses a build context. This is the set of files made available to the Docker build process.
We do not need to send local virtual environments, Python cache files or Git metadata as part of this build context.
The .dockerignore file excludes these unnecessary files.
This helps keep the build context smaller and avoids copying irrelevant files into the image.
9. How Does GitHub Actions Automate Continuous Integration?
Now comes the automation part.
Instead of manually building and pushing Docker images every time the application changes, I configured GitHub Actions to perform this process automatically.
The workflow is located at:
.github/workflows/docker-build.yml
It contains two jobs:
build-and-pushdeploy
Let's understand the complete workflow.
9.1 What Triggers the Workflow?
name: Build, Push, and Deploy
on:
push:
branches:
- main
This defines the event that triggers the workflow.
Whenever a commit is pushed to the main branch, GitHub Actions starts executing the workflow.
This means we do not need to manually start the build and deployment process for every change.
9.2 How Are Concurrent Deployments Managed?
concurrency:
group: fastapi-production-deployment
cancel-in-progress: false
This configuration helps prevent multiple workflow runs in the same concurrency group from deploying to production simultaneously.
Why is this important?
Imagine that two developers push changes close together.
Without deployment coordination, two deployment processes could attempt to modify the same production containers at the same time.
That could create unexpected results.
The concurrency configuration helps serialize access to the deployment workflow rather than allowing overlapping deployments.
9.3 Which Permissions Does the Workflow Need?
permissions:
contents: read
This gives the workflow read-only access to repository contents.
It follows the principle of providing only the permissions required for the workflow.
9.4 How Does the Build-and-Push Job Start?
jobs:
build-and-push:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v4
The build-and-push job runs on a GitHub-hosted Ubuntu runner.
The first step checks out the repository so the runner can access the project files.
The runner is the environment where the GitHub Actions workflow executes.
9.5 How Does GitHub Actions Authenticate with Docker Hub?
- name: Log in to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
Before pushing a Docker image, the workflow needs to authenticate with Docker Hub.
I used GitHub Actions Secrets to store the Docker Hub username and access token.
The secret values are not hardcoded inside the workflow.
The required secrets are:
DOCKERHUB_USERNAMEDOCKERHUB_TOKEN
This avoids committing authentication credentials to the source-code repository.
9.6 How Are Docker Images Built and Tagged?
- name: Build and Push Docker Image
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
run: |
IMAGE="$DOCKERHUB_USERNAME/fastapi-cloud"
docker build \
-t "$IMAGE:latest" \
-t "$IMAGE:${GITHUB_SHA}" \
.
docker push "$IMAGE:latest"
docker push "$IMAGE:${GITHUB_SHA}"
This is where the Docker image is created and published.
First, the workflow defines the image name:
IMAGE="$DOCKERHUB_USERNAME/fastapi-cloud"
Then it executes the Docker build command.
Notice that I use two image tags.
1. latest
-t "$IMAGE:latest"
This tag represents the latest image published under that tag.
However, the latest tag is mutable. Its reference can point to a different image after another build.
2. Git commit SHA
-t "$IMAGE:${GITHUB_SHA}"
This tag uses the Git commit SHA associated with the current workflow run.
For example, if a commit triggers the workflow, its image can be identified by that commit-specific tag.
Why did I choose commit-SHA tagging?
Because identifying the exact image deployed to production is important.
Instead of relying on a moving latest tag, the deployment process can retrieve the image associated with a particular source-code commit.
Finally, the workflow pushes both tags:
docker push "$IMAGE:latest"
docker push "$IMAGE:${GITHUB_SHA}"
The resulting images are stored in Docker Hub.
My Docker Hub repository:
madhucheran/fastapi-cloud
At this point, the CI stage is complete.
The application has been packaged into a Docker image and published to the registry.
10. How Does the Pipeline Deploy to AWS EC2?
After the build job successfully completes, the deployment job starts.
Here is the relevant configuration:
deploy:
needs: build-and-push
runs-on: ubuntu-latest
The important part is:
needs: build-and-push
This creates a dependency between the two jobs.
The deployment job runs only after the build-and-push job completes successfully.
This prevents deployment from starting when the image build or publishing stage fails.
Now let's understand how GitHub Actions communicates with the EC2 instance.
10.1 How Does GitHub Actions Connect to EC2 Using SSH?
- name: Prepare deployment directory on EC2
uses: appleboy/ssh-action@v1.0.3
with:
host: ${{ secrets.EC2_HOST }}
username: ubuntu
key: ${{ secrets.EC2_SSH_KEY }}
script: |
mkdir -p /home/ubuntu/deployment
The GitHub Actions runner connects to the Ubuntu EC2 instance using SSH.
The connection details are supplied through GitHub Secrets.
EC2_HOSTcontains the EC2 public IP address or DNS name.EC2_SSH_KEYcontains the private SSH key.ubuntuis the SSH username for the Ubuntu EC2 environment.
The command creates a deployment directory:
mkdir -p /home/ubuntu/deployment
This directory is used to store the deployment script.
10.2 How Is the Deployment Script Copied to EC2?
- name: Copy deployment script to EC2
uses: appleboy/scp-action@v0.1.7
with:
host: ${{ secrets.EC2_HOST }}
username: ubuntu
key: ${{ secrets.EC2_SSH_KEY }}
source: "scripts/deploy.sh"
target: "/home/ubuntu/deployment/"
strip_components: 1
overwrite: true
SSH is used to connect to the server, while SCP is used to transfer files securely.
Here, the workflow copies only scripts/deploy.sh to the EC2 deployment directory.
The strip_components: 1 setting removes the leading scripts/ directory from the copied path, leaving deploy.sh directly inside the target directory.
This keeps the deployment script separate from the application source code.
10.3 How Is the Deployment Script Executed?
- name: Deploy versioned Docker image
uses: appleboy/ssh-action@v1.0.3
with:
host: ${{ secrets.EC2_HOST }}
username: ubuntu
key: ${{ secrets.EC2_SSH_KEY }}
script: |
chmod +x /home/ubuntu/deployment/deploy.sh
bash /home/ubuntu/deployment/deploy.sh \
"${{ secrets.DOCKERHUB_USERNAME }}/fastapi-cloud:${{ github.sha }}"
This is the final stage of the GitHub Actions workflow.
The workflow makes the script executable and executes it with the commit-SHA Docker image as an argument.
For example:
madhucheran/fastapi-cloud:<commit-sha>
That image reference is passed to the deployment script.
The script now takes responsibility for the actual deployment on EC2.
This separation is useful because GitHub Actions handles orchestration, while Bash handles the server-side deployment logic.
11. How Does the Bash Deployment Script Work?
This is one of the most important files in the project.
The deployment logic is maintained in:
scripts/deploy.sh
Its responsibility is to:
- Pull the new Docker image.
- Start a candidate container.
- Verify its health.
- Preserve the existing production container.
- Promote the new container.
- Verify production deployment.
- Restore the previous version if production verification fails.
Let's break it down.
11.1 Why Use Strict Shell Options?
#!/bin/bash
set -Eeuo pipefail
The script uses strict Bash execution settings.
-e: Exit when an unhandled command fails.-E: Allow theERRtrap to be inherited in appropriate shell contexts.-u: Treat references to unset variables as errors.-o pipefail: Make a pipeline fail when a command within it fails.
These settings help catch errors instead of silently continuing with an unsuccessful deployment.
11.2 How Are Deployment Variables Defined?
NEW_IMAGE="${1:?Usage: deploy.sh <docker-image:tag>}"
APP="fastapi-container"
CANDIDATE="fastapi-candidate"
PREVIOUS="fastapi-previous"
PROMOTION_STARTED=false
DEPLOYMENT_SUCCESS=false
The first line receives the Docker image reference passed by GitHub Actions.
The script also defines three container names.
| Container | Responsibility |
|---|---|
fastapi-container |
Production application |
fastapi-candidate |
Newly pulled application being verified |
fastapi-previous |
Previous production container retained for recovery |
Two Boolean variables track the deployment state.
PROMOTION_STARTED indicates whether the script has begun replacing production.
DEPLOYMENT_SUCCESS indicates whether the new production version passed verification.
These variables help determine whether rollback handling is necessary.
11.3 How Does the Script Check Container Health?
wait_for_healthy() {
local container="$1"
local status=""
for attempt in $(seq 1 20); do
status=$(sudo docker inspect \
--format='{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' \
"$container" 2>/dev/null || true)
echo "$container health: ${status:-unknown}"
if [ "$status" = "healthy" ]; then
return 0
fi
if [ "$status" = "unhealthy" ] || [ "$status" = "exited" ]; then
return 1
fi
sleep 3
done
return 1
}
This function is responsible for checking the health status of a Docker container.
Let's understand the logic.
First, it receives a container name.
Then it executes:
sudo docker inspect
Docker Inspect retrieves detailed information about a container.
The format expression checks whether Docker has a health status available.
If it does, the function returns the health status. Otherwise, it returns the container's running state.
The function handles three important conditions:
healthy: The application has passed its Docker health check.unhealthy: The health check has failed repeatedly.exited: The container has stopped.
The script retries the check up to 20 times and waits three seconds between attempts when the container is still starting.
If the application never becomes healthy, the function returns a failure.
This function is reused during both candidate verification and production verification.
11.4 How Does the Rollback Function Restore the Previous Container?
rollback() {
echo "Deployment failed. Starting rollback..."
if sudo docker inspect "$PREVIOUS" >/dev/null 2>&1; then
sudo docker rm -f "$APP" 2>/dev/null || true
sudo docker rename "$PREVIOUS" "$APP"
elif sudo docker inspect "$APP" >/dev/null 2>&1; then
echo "Previous container was not renamed. Restarting it."
else
echo "No previous container available for rollback."
return 1
fi
sudo docker start "$APP" || return 1
if wait_for_healthy "$APP" && \
curl -fsS http://localhost:8000/health; then
echo "Rollback successful."
return 0
fi
echo "CRITICAL: Rollback health verification failed."
return 1
}
This function is responsible for restoring the previous production container when the new production deployment fails.
First, it checks whether the previous container exists.
If it exists, the script:
- Removes the failed production container if present.
- Renames the previous container back to
fastapi-container. - Starts the restored production container.
- Checks its Docker health status.
- Sends an HTTP request to the production health endpoint.
The final HTTP check is important because we want to verify that the application responds through the production port mapping, not simply that the container has started.
If the restored application passes both checks, rollback is considered successful.
If there is no previous container available, the script reports that recovery is unavailable.
This is particularly relevant during the first deployment because there may not yet be a previous production version.
11.5 How Are Unexpected Deployment Errors Handled?
on_error() {
local exit_code=$?
trap - ERR
echo "Unexpected deployment error: exit code $exit_code"
if [ "$PROMOTION_STARTED" = true ] && \
[ "$DEPLOYMENT_SUCCESS" = false ]; then
rollback || true
fi
exit "$exit_code"
}
trap on_error ERR
This part defines an error handler.
When an eligible unhandled command error triggers the ERR trap, the script records the exit code and checks the deployment state.
If production promotion has started but the deployment has not succeeded, the script attempts rollback.
The trap is disabled inside the error handler to avoid recursively triggering itself.
This is a safety mechanism for unexpected errors during promotion.
The script also has an explicit rollback call for production health verification failures, so those expected failure paths do not depend solely on the trap.
12. How Does the Deployment Process Work Step by Step?
Now let's understand the actual execution sequence.
Step 1 – How Does EC2 Pull the New Docker Image?
sudo docker pull "$NEW_IMAGE"
The EC2 instance downloads the specific Docker image from Docker Hub.
Remember that the image reference includes the Git commit SHA.
This means the server retrieves the image associated with the commit that triggered this deployment, rather than simply pulling whichever image currently has the latest tag.
This assumes the image is publicly accessible or that the EC2 instance already has valid Docker Hub authentication configured.
Step 2 – Why Remove a Stale Candidate Container?
sudo docker rm -f "$CANDIDATE" 2>/dev/null || true
Before starting a new candidate, the script removes an older candidate container if one exists.
The || true prevents the script from failing when there is no existing candidate to remove.
Step 3 – How Is the Candidate Container Started?
sudo docker run -d \
--name "$CANDIDATE" \
-p 127.0.0.1:8001:8000 \
--health-cmd='curl -fsS http://localhost:8000/health || exit 1' \
--health-interval=5s \
--health-timeout=3s \
--health-retries=3 \
--health-start-period=5s \
"$NEW_IMAGE"
This command starts the new application as a candidate container.
There are several important options here.
-d
Runs the container in detached mode, meaning it runs in the background.
--name "$CANDIDATE"
Assigns the name fastapi-candidate to the container.
-p 127.0.0.1:8001:8000
This is an important networking configuration.
It maps:
- Host port:
8001 - Container port:
8000 - Host binding address:
127.0.0.1
The candidate is accessible locally on the EC2 instance through port 8001.
It is not exposed directly on the EC2 instance's public network interface through this port mapping.
Why use a separate port?
Because the existing production application is using port 8000.
We need to validate the new version without immediately replacing the running application.
Health check options
The command also configures a Docker health check.
It sends a request to the application's /health endpoint and checks whether it responds successfully.
The candidate container is now running separately from the current production container.
Step 4 – How Is the Candidate Verified?
if ! wait_for_healthy "$CANDIDATE"; then
echo "Candidate health check failed."
sudo docker logs "$CANDIDATE" || true
sudo docker rm -f "$CANDIDATE" || true
exit 1
fi
echo "Candidate is healthy."
The deployment script calls the health verification function.
If the candidate becomes healthy, the deployment continues.
If it fails:
- The script displays the candidate's logs.
- It removes the candidate container.
- It exits with a failure status.
An important advantage of this step is that the current production container has not yet been stopped or replaced.
So a candidate verification failure leaves the existing production application untouched.
Step 5 – How Is the Current Production Container Preserved?
PROMOTION_STARTED=true
sudo docker rm -f "$PREVIOUS" 2>/dev/null || true
if sudo docker inspect "$APP" >/dev/null 2>&1; then
sudo docker stop "$APP"
sudo docker rename "$APP" "$PREVIOUS"
fi
Once the candidate has passed its health check, the script begins production promotion.
First, it marks promotion as started.
Next, it removes any older retained previous container.
Then it checks whether the current production container exists.
If it does:
- The existing production container is stopped.
- It is renamed to
fastapi-previous.
The previous container is retained so it can be restored if the new production version fails verification.
Step 6 – How Is the Candidate Promoted to Production?
sudo docker rm -f "$CANDIDATE"
sudo docker run -d \
--name "$APP" \
--restart unless-stopped \
-p 8000:8000 \
--health-cmd='curl -fsS http://localhost:8000/health || exit 1' \
--health-interval=5s \
--health-timeout=3s \
--health-retries=3 \
--health-start-period=5s \
"$NEW_IMAGE"
After preserving the previous version, the script removes the candidate container.
It then starts a new production container using the same image that passed candidate verification.
The new container is named fastapi-container.
What does --restart unless-stopped do?
It configures Docker to restart the container automatically after eligible Docker daemon or host restarts, unless the container was explicitly stopped.
-p 8000:8000
This maps the host's port 8000 to the application's port 8000 inside the container.
Port 8000 is the production application port.
At this point, the new application is running as the production container.
Step 7 – How Is the Production Deployment Verified?
if ! wait_for_healthy "$APP" || \
! curl -fsS http://localhost:8000/health; then
echo "Production health verification failed."
rollback
exit 1
fi
Starting the container is not enough.
We need to verify that the newly promoted application is healthy.
The script performs two checks:
First: It checks the Docker container's health status.
Second: It sends an HTTP request directly from the EC2 host to:
http://localhost:8000/health
Both checks must succeed.
If either fails, the rollback function is called.
This is the most important failure-handling stage of the deployment process.
Step 8 – How Is a Successful Deployment Recorded?
DEPLOYMENT_SUCCESS=true
trap - ERR
echo "===================================="
echo "Deployment successful!"
echo "Image: $NEW_IMAGE"
echo "===================================="
After production verification succeeds, the script marks the deployment as successful and disables the error trap.
The previous production container is retained as fastapi-previous for recovery during a subsequent deployment failure.
The deployment script now finishes successfully.
13. How Do the Containers Move Through the Deployment Lifecycle?
Let's summarize how the three containers are used during deployment.
| Deployment stage | Production | Candidate | Previous |
|---|---|---|---|
| Before deployment | Running | Absent | Possibly retained |
| Candidate verification | Running | Running on port 8001 | Possibly retained |
| Promotion | Stopped and renamed | Removed | Previous production |
| After successful deployment | New version running on port 8000 | Absent | Old version retained |
| After successful rollback | Restored old version running | Absent | Restored to production name |
This container naming strategy makes it easier to understand which version is serving production traffic and which version is available for recovery.
14. Is This True Blue-Green Deployment?
While implementing this project, I explored the idea of blue-green deployment.
The project uses an important concept from that approach: validating a separate candidate application before promoting it to production.
However, it is important to understand the distinction.
In true zero-downtime blue-green deployment, two environments are maintained and traffic is switched between them, typically using a reverse proxy or load balancer.
In my current implementation:
- The candidate is verified on port 8001.
- The current production container is stopped.
- The previous container is renamed.
- The candidate is removed.
- A new production container is started on port 8000.
There can be a short interruption during this replacement process.
Therefore, this is more accurately described as a candidate-based deployment with health verification and rollback, rather than a true zero-downtime blue-green deployment.
Understanding this distinction is important when discussing the project technically.
15. How Can We Run the Application Locally with Docker?
Before using GitHub Actions, the application can also be tested locally using Docker.
Build the image:
docker build -t fastapi-cloud .
Start the container:
docker run --rm -p 8000:8000 fastapi-cloud
Now open another terminal and run:
curl http://localhost:8000/health
Expected response:
{"status":"healthy"}
This confirms that the application is responding through the Docker port mapping.
16. Which GitHub Actions Secrets Are Required?
For the automated workflow to communicate with Docker Hub and AWS, I configured the following repository secrets.
Navigate to:
GitHub Repository → Settings → Secrets and variables → Actions
Add these secrets:
| Secret | Purpose |
|---|---|
DOCKERHUB_USERNAME |
Docker Hub username |
DOCKERHUB_TOKEN |
Docker Hub access token |
EC2_HOST |
EC2 public IPv4 address or DNS name |
EC2_SSH_KEY |
Private SSH key for connecting to EC2 |
Never commit these credentials or private keys to the repository.
The EC2 instance must also have Docker installed, the deployment user must be able to execute the required Docker commands, and the host needs curl for the final HTTP health verification.
The image must be publicly accessible from the EC2 host or the host must be authenticated to Docker Hub before the docker pull command runs.
For external testing, the EC2 security group must allow the required application traffic on port 8000. SSH access should be restricted to trusted source IP addresses.
17. How Do We Verify the Deployment?
After pushing a new commit to the main branch, the GitHub Actions workflow should start automatically.
I use the GitHub Actions tab to inspect the build and deployment jobs.
The important things to verify are:
1. GitHub Actions
Both build-and-push and deploy jobs should complete successfully.
2. Docker Hub
The repository should contain the newly pushed image tags:
latest- The Git commit SHA.
3. EC2 instance
To inspect the containers:
sudo docker ps -a
To inspect container health:
sudo docker inspect fastapi-container
4. Application endpoint
From a machine that can reach the EC2 instance:
curl http://<EC2_PUBLIC_IP>:8000/health
Expected response:
{"status":"healthy"}
The combination of GitHub Actions status, Docker image tags, container health and HTTP response provides a way to verify the complete deployment flow.
18. What Did I Learn While Building This Project?
Building this project helped me understand that DevOps is not simply about connecting multiple tools.
The real learning comes from understanding how each component communicates with the next component and how the system behaves when something fails.
Some important concepts I learned through this implementation:
GitHub Actions
I understood how workflows are triggered, how jobs depend on one another and how secrets are used in automated pipelines.
Docker
I learned how a Dockerfile defines the application environment, how images are built and tagged, and how containers are started and monitored.
Docker Hub
I understood how a container registry separates image creation from image deployment.
AWS EC2 and SSH
I learned how a GitHub-hosted runner can securely connect to a remote Linux server and execute deployment commands.
Bash scripting
Writing the deployment script helped me understand shell variables, functions, conditions, error handling, exit codes and Docker commands.
Health checks
I understood why verifying the actual application response is more meaningful than checking only whether a container is running.
Rollback handling
I learned how retaining the previous container can help recover from an unsuccessful production deployment.
Most importantly, I started thinking about deployment failure scenarios instead of focusing only on successful execution.
19. What Are the Current Limitations and Planned Improvements?
This project is a practical learning and portfolio project. It is not yet a hardened production architecture.
There are several improvements I plan to introduce.
1. Multi-stage Docker builds
The current Dockerfile uses a single build stage.
I plan to introduce multi-stage builds to improve image construction and reduce unnecessary image contents.
2. Terraform – Infrastructure as Code
Currently, the EC2 infrastructure is configured separately.
I plan to use Terraform to define and provision the required AWS infrastructure through code.
3. Docker Compose
The current deployment script manages containers directly using docker run.
I want to explore Docker Compose to manage the application container lifecycle more cleanly.
4. True zero-downtime deployment
The current deployment has a brief interruption during production container replacement.
I plan to introduce a reverse proxy or traffic-switching mechanism to implement a more complete blue-green deployment architecture.
5. Improved observability and testing
The current workflow builds and publishes the image but does not yet run an automated application test suite. I also plan to introduce better deployment logging and deliberate failure-injection tests to verify the rollback process.
These improvements will help me take the project closer to a production-oriented DevOps architecture.
Frequently Asked Questions
What is a FastAPI CI/CD pipeline?
A FastAPI CI/CD pipeline automates the process of building, packaging and deploying a FastAPI application. In this project, GitHub Actions builds Docker images and publishes them to Docker Hub before initiating deployment to AWS EC2.
Why use Docker for a FastAPI application?
Docker packages the FastAPI application and its dependencies into a container image. This provides a consistent runtime environment when the application is run on different systems.
Why use GitHub Actions for CI/CD?
GitHub Actions automates workflows in response to repository events. In this project, a push to the main branch triggers the image build and publishing jobs, followed by the deployment job when the build job succeeds.
Why are Docker images tagged with the Git commit SHA?
A commit-SHA tag links a Docker image to the source-code commit that produced it. The deployment job uses that specific tag instead of relying on the mutable latest tag, making the deployed image easier to trace.
How does deployment rollback work in this project?
The deployment script retains the previous production container as fastapi-previous. If the newly promoted application fails production health verification, the script attempts to restore the previous container and checks its health.
What happens if the candidate container fails its health check?
The script displays the candidate container logs, removes the candidate and exits with a failure status. Because this check happens before the current production container is stopped, the existing production application is left in place.
Does this project implement zero-downtime blue-green deployment?
No. The candidate is checked on port 8001, but the current production container is stopped before the replacement container starts on port 8000. This can cause a brief service interruption. A traffic-switching component, such as a reverse proxy or load balancer, is a planned improvement.
Which AWS service hosts the FastAPI application?
The application runs in a Docker container on an Ubuntu-based AWS EC2 instance. GitHub Actions connects to the instance through SSH to transfer and execute the deployment script.
What improvements are planned for this project?
Planned improvements include multi-stage Docker builds, Terraform for infrastructure as code, Docker Compose for container management, a traffic-switching mechanism for zero-downtime deployment, and more deployment testing and observability.
Conclusion
This project gave me practical exposure to building an automated CI/CD pipeline from the ground up.
I started with a simple FastAPI application and connected it with Docker, GitHub Actions, Docker Hub and AWS EC2.
Along the way, I learned how application code becomes a Docker image, how that image is published to a registry, how GitHub Actions communicates with a remote server, and how deployment scripts can manage application updates and failures.
There is still more to learn and improve, but building this project helped me connect individual DevOps concepts into one working workflow.
For anyone learning DevOps, my recommendation is simple:
Don't just learn what each tool does. Build something that makes the tools work together.
Keep learning. Keep building. Keep improving.
Thanks for reading!
Let's Learn Together.
Project Repository:
https://github.com/madhucheran/fastapi-docker-pipeline
Docker Hub:
https://hub.docker.com/r/madhucheran/fastapi-cloud
About the author
𝐈'𝐦 𝐚𝐧 𝐞𝐧𝐠𝐢𝐧𝐞𝐞𝐫𝐢𝐧𝐠 𝐬𝐭𝐮𝐝𝐞𝐧𝐭 𝐡𝐨𝐨𝐤𝐞𝐝 𝐨𝐧 𝐃𝐞𝐯𝐎𝐩𝐬, 𝐬𝐚𝐢𝐥𝐢𝐧𝐠 𝐭𝐡𝐫𝐨𝐮𝐠𝐡 𝐭𝐡𝐢𝐬 𝐬𝐞𝐚 𝐨𝐟 𝐭𝐞𝐜𝐡 𝐰𝐢𝐭𝐡 𝐞𝐱𝐜𝐢𝐭𝐞𝐦𝐞𝐧𝐭 𝐚𝐧𝐝 𝐜𝐮𝐫𝐢𝐨𝐬𝐢𝐭𝐲.....
❝𝓑𝓾𝓽.𝓘𝓽 𝓒𝓪𝓷 𝓗𝓪𝓹𝓹𝓮𝓷❞ -𝓜𝓪𝓭𝓱𝓾𝓬𝓱𝓮𝓻𝓪𝓷
Comments
Join the discussionNo comments yet. Be the first to comment.
DevOps Hands-On Projects
A practical journey through DevOps engineering, featuring real-world projects, step-by-step implementations, architecture breakdowns, CI/CD automation, Docker, AWS, Infrastructure as Code, and deployment strategies. Learn by building, experimenting, and understanding how DevOps tools work together.
