Skip to content

About

An end-to-end DevOps project implementing automated testing, Docker containerization, container image publishing, and continuous deployment of a FastAPI application to AWS EC2 using GitHub Actions.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

11 Commits

Folders and files

Repository files navigation

πŸš€ CI/CD FastAPI AWS Deployment

An end-to-end DevOps project implementing automated testing, Docker containerization, container image publishing, and continuous deployment of a FastAPI application to AWS EC2 using GitHub Actions.

CI/CD Pipeline Docker AWS Python FastAPI


πŸ“Œ Overview

CI/CD FastAPI AWS Deployment is a practical DevOps project designed to demonstrate how a Python web application can move from source code to a running cloud environment through an automated CI/CD pipeline.

Instead of manually copying application files to an AWS server, the project automates the complete deployment lifecycle:

Developer
    β”‚
    β”‚ git push
    β–Ό
GitHub Repository
    β”‚
    β–Ό
GitHub Actions
    β”‚
    β”œβ”€β”€ Install dependencies
    β”œβ”€β”€ Run automated tests
    β”œβ”€β”€ Build Docker image
    └── Push image
            β”‚
            β–Ό
    GitHub Container Registry
            β”‚
            β”‚ docker pull
            β–Ό
        AWS EC2
            β”‚
            β–Ό
       Docker Engine
            β”‚
            β–Ό
     FastAPI + Uvicorn
            β”‚
            β–Ό
       GET /health
            β”‚
            β–Ό
      HTTP 200 Healthy

The project demonstrates the fundamental DevOps lifecycle:

Source Control β†’ Continuous Integration β†’ Containerization β†’ Artifact Registry β†’ Continuous Deployment β†’ Cloud Infrastructure β†’ Application Verification


πŸ—οΈ Architecture

flowchart LR

    Dev["πŸ‘¨β€πŸ’» Developer"]

    GitHub["GitHub Repository"]

    Actions["GitHub Actions"]

    Tests["pytest<br/>Automated Tests"]

    Build["Docker Build"]

    GHCR["GitHub Container Registry<br/>GHCR"]

    EC2["AWS EC2<br/>Amazon Linux 2023"]

    Docker["Docker Engine"]

    FastAPI["FastAPI<br/>Uvicorn"]

    Health["GET /health"]

    Verified["βœ… Deployment Verified"]

    Dev -->|"git push main"| GitHub

    GitHub --> Actions

    Actions --> Tests

    Tests -->|"Tests pass"| Build

    Build --> GHCR

    Actions -->|"SSH deployment"| EC2

    GHCR -->|"docker pull"| EC2

    EC2 --> Docker

    Docker --> FastAPI

    FastAPI --> Health

    Health -->|"HTTP 200"| Verified
Loading

πŸ”„ End-to-End Deployment Flow

The deployment process consists of the following stages:

1. Developer pushes code

A change is committed and pushed to the main branch.

git add .
git commit -m "Update application"
git push origin main

This triggers the GitHub Actions workflow.


2. GitHub Actions starts the CI pipeline

GitHub Actions provisions an Ubuntu runner and:

  • checks out the repository
  • installs Python 3.12
  • installs project dependencies
  • executes the test suite
GitHub
   ↓
GitHub Actions
   ↓
Checkout
   ↓
Python 3.12
   ↓
Dependencies
   ↓
pytest

If the tests fail, the deployment does not proceed.


3. Docker image is built

After successful tests, Docker builds the application image using the project's Dockerfile.

docker build -t cicd-fastapi .

The image packages:

  • Python runtime
  • application dependencies
  • FastAPI application
  • Uvicorn server

This creates a consistent artifact that can run in different environments.


4. Image is published to GHCR

GitHub Actions authenticates to GitHub Container Registry using the built-in GITHUB_TOKEN.

The image is published as:

ghcr.io/pmman-sudo/cicd-fastapi-aws:main

GHCR therefore acts as the centralized container artifact repository.


5. GitHub Actions connects to EC2

Once the image has been published, the deployment job connects to the AWS EC2 instance using SSH.

The private key is retrieved from GitHub Secrets rather than being stored in the repository.


6. EC2 pulls the new image

The EC2 server executes:

docker pull ghcr.io/pmman-sudo/cicd-fastapi-aws:main

The server therefore deploys the same container image that was produced by CI.


7. Previous container is replaced

The existing application container is removed:

docker rm -f cicd-fastapi || true

A new container is started:

docker run -d \
  --name cicd-fastapi \
  --restart unless-stopped \
  -p 8000:8000 \
  ghcr.io/pmman-sudo/cicd-fastapi-aws:main

The port mapping is:

EC2 port 8000
      β”‚
      β–Ό
Container port 8000
      β”‚
      β–Ό
FastAPI / Uvicorn

8. Deployment is verified

The deployment script waits for the application to start and performs:

curl -f http://localhost:8000/health

A successful response:

{
  "status": "healthy"
}

confirms that the newly deployed application is responding.


πŸ§ͺ CI/CD Pipeline

The workflow is divided into two logical stages.

flowchart TD

    A["Git Push / Pull Request"] --> B["GitHub Actions"]

    B --> C["Checkout Repository"]

    C --> D["Setup Python 3.12"]

    D --> E["Install Dependencies"]

    E --> F["Run pytest"]

    F -->|"Tests pass"| G["Login to GHCR"]

    G --> H["Generate Docker Metadata"]

    H --> I["Build Docker Image"]

    I --> J["Push Image to GHCR"]

    J --> K["Deploy Job"]

    K --> L["Start SSH Agent"]

    L --> M["Connect to EC2"]

    M --> N["Pull Docker Image"]

    N --> O["Remove Previous Container"]

    O --> P["Start New Container"]

    P --> Q["Health Check"]

    Q --> R["βœ… Deployment Successful"]
Loading

πŸ”¬ Continuous Integration

Every push or pull request targeting main triggers the CI workflow.

The CI stage performs:

  1. Repository checkout
  2. Python environment setup
  3. Dependency installation
  4. Automated testing
  5. Docker image creation
  6. Container image publishing

The important principle is:

Code should not be deployed if the automated tests fail.

This is enforced through the job dependency:

deploy:
  needs: test-and-build

Therefore:

Tests PASS
    ↓
Build
    ↓
Publish
    ↓
Deploy

but:

Tests FAIL
    ↓
Pipeline stops
    ↓
Deployment does not occur

πŸš€ Continuous Deployment

The deployment stage automatically updates the application running on EC2.

The deployment process:

GitHub Actions
      β”‚
      β”‚ SSH
      β–Ό
AWS EC2
      β”‚
      β”œβ”€β”€ docker pull
      β”‚
      β”œβ”€β”€ docker rm
      β”‚
      β”œβ”€β”€ docker run
      β”‚
      └── curl /health

This eliminates the need to manually SSH into the server and deploy every new version.


🐳 Docker

The application is containerized using Docker.

The Dockerfile uses a lightweight Python image:

FROM python:3.12-slim

WORKDIR /app

COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt

COPY app ./app

EXPOSE 8000

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

Why python:3.12-slim?

A slim image provides the Python runtime while reducing unnecessary operating-system packages and image size compared with a full Python image.


Why copy requirements.txt first?

The Dockerfile performs:

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

before:

COPY app ./app

This improves Docker layer caching.

If application source code changes but dependencies remain unchanged, Docker can reuse the dependency installation layer.


Why 0.0.0.0?

Uvicorn is started with:

--host 0.0.0.0

This allows the application to accept connections through the container's network interface rather than being restricted to the container's loopback interface.


πŸ“¦ Docker Compose

The project also includes:

docker-compose.yml

This provides a convenient way to define and run the application locally using Docker Compose.

The project therefore demonstrates both:

  • direct Docker execution
  • Docker Compose configuration

🧹 .dockerignore

The .dockerignore file prevents unnecessary or sensitive files from being included in the Docker build context.

Example:

venv/
**__pycache__/
.pytest_cache/
.git/
.gitignore
.env
tests/

This helps:

  • reduce build context size
  • improve build performance
  • prevent unnecessary files from entering the image
  • reduce the risk of accidentally including local secrets

πŸ§ͺ Testing

The project uses pytest for automated testing.

Tests are executed locally with:

pytest

and automatically within GitHub Actions.

This ensures that application changes are tested before deployment.


☁️ AWS Infrastructure

The deployment environment consists of:

Component Purpose
AWS EC2 Hosts the application
Amazon Linux 2023 Server operating system
Docker Engine Runs the application container
Security Group Controls inbound/outbound traffic
SSH Secure administrative/deployment access
Port 8000 FastAPI application endpoint

The EC2 instance runs the container:

cicd-fastapi

with:

EC2 :8000 β†’ Docker :8000 β†’ FastAPI

πŸ” Secrets Management

Deployment credentials are stored in GitHub repository secrets rather than committed to source control.

The deployment uses:

EC2_HOST
EC2_USER
EC2_SSH_KEY

The private SSH key is supplied to GitHub Actions through:

${{ secrets.EC2_SSH_KEY }}

This prevents the private key from being exposed in the repository.

Security principle

❌ Private key in Git repository

❌ Private key inside Docker image

❌ Private key inside source code

βœ… Private key stored in GitHub Secrets

πŸ”’ Security Considerations

The project incorporates several foundational security practices:

  • SSH private key stored in GitHub Secrets
  • .env excluded from Docker build context
  • .git excluded from Docker build context
  • automated tests executed before deployment
  • SSH host verification
  • EC2 security-group controlled access
  • Docker container isolation
  • deployment performed through an authenticated SSH connection

However, this project should be considered a production-style portfolio deployment, rather than a fully hardened production architecture.

A real production environment would require additional controls.


πŸ›‘οΈ Potential Security Improvements

Future hardening could include:

  • HTTPS/TLS
  • AWS Application Load Balancer
  • restricted Security Group rules
  • AWS IAM roles
  • immutable container image digests
  • container vulnerability scanning
  • secret rotation
  • centralized logging
  • CloudWatch monitoring
  • intrusion detection
  • automated rollback
  • deployment approvals
  • private subnets
  • bastion host or SSM-based administration
  • WAF protection

πŸ“ Repository Structure

cicd-fastapi-aws/
β”‚
β”œβ”€β”€ .github/
β”‚   └── workflows/
β”‚       └── ci-cd.yml
β”‚
β”œβ”€β”€ app/
β”‚   └── main.py
β”‚
β”œβ”€β”€ tests/
β”‚   └── ...
β”‚
β”œβ”€β”€ .dockerignore
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ requirements.txt
└── README.md

πŸ› οΈ Technology Stack

Application

  • Python 3.12
  • FastAPI
  • Uvicorn

Testing

  • pytest

Containerization

  • Docker
  • Docker Compose

CI/CD

  • GitHub Actions

Container Registry

  • GitHub Container Registry

Cloud

  • Amazon Web Services
  • Amazon EC2
  • Amazon Linux 2023

Deployment

  • SSH
  • Docker

Source Control

  • Git
  • GitHub

πŸ’» Local Development

Clone the repository:

git clone https://github.com/pmman-sudo/cicd-fastapi-aws.git
cd cicd-fastapi-aws

Create a virtual environment:

python -m venv venv

Activate it on Windows:

.\venv\Scripts\Activate.ps1

Install dependencies:

pip install -r requirements.txt

Run the application:

uvicorn app.main:app --reload

The API should then be available at:

http://localhost:8000

🐳 Running with Docker

Build the image:

docker build -t cicd-fastapi .

Run the container:

docker run --rm -p 8000:8000 cicd-fastapi

Verify the application:

curl http://localhost:8000/health

Expected:

{
  "status": "healthy"
}

πŸ“¦ Running the Published Image

The published image is available through GHCR:

ghcr.io/pmman-sudo/cicd-fastapi-aws:main

Pull it:

docker pull ghcr.io/pmman-sudo/cicd-fastapi-aws:main

Run it:

docker run --rm -p 8000:8000 \
  ghcr.io/pmman-sudo/cicd-fastapi-aws:main

πŸ“Š Validation & Results

The completed implementation successfully demonstrated:

Local Environment

  • FastAPI application startup
  • Docker image creation
  • Docker container execution
  • /health endpoint validation

CI/CD

  • GitHub Actions workflow execution
  • Automated pytest execution
  • Docker image creation within CI
  • GHCR authentication
  • Container image publication
  • Deployment job execution

AWS

  • EC2 instance configuration
  • Amazon Linux 2023 administration
  • Docker Engine installation
  • SSH authentication
  • GHCR image retrieval
  • Docker container deployment
  • Application health verification

The deployed application successfully returned:

{
  "status": "healthy"
}

with HTTP status:

200 OK

πŸ“ˆ Engineering Challenges Solved

During development, several practical DevOps problems were encountered and resolved.

Docker port conflict

A local container initially failed because port 8000 was already occupied.

The issue was resolved by identifying the existing container and using an alternative host port where necessary:

docker run --rm -p 8001:8000 ...

This reinforced the distinction between:

HOST PORT : CONTAINER PORT

SSH authentication troubleshooting

The EC2 deployment involved troubleshooting:

  • incorrect SSH usernames
  • SSH key paths
  • Windows PowerShell path handling
  • public/private key authentication
  • EC2 connectivity
  • Security Group access

The final deployment successfully authenticated to the EC2 instance.


Docker installation on EC2

The EC2 instance initially did not have Docker available.

Docker was installed, started, enabled as a system service, and configured so the ec2-user could interact with Docker without requiring sudo for normal container operations.


CI/CD deployment validation

The deployment was validated end-to-end by checking:

docker ps

then:

docker logs cicd-fastapi

and finally:

curl http://localhost:8000/health

This confirmed that the container was running and the application was responding correctly.


🎯 What This Project Demonstrates

This project demonstrates practical experience with:

  • Git workflows
  • GitHub repository management
  • GitHub Actions
  • CI/CD pipeline design
  • automated testing
  • Docker image creation
  • Docker container management
  • Docker Compose
  • GitHub Container Registry
  • AWS EC2
  • Amazon Linux
  • Linux administration
  • SSH authentication
  • GitHub Secrets
  • deployment automation
  • application health checks
  • cloud deployment
  • DevOps troubleshooting

More importantly, it demonstrates the ability to connect these technologies into a working deployment system rather than learning each tool in isolation.


🧠 Key DevOps Concepts Learned

Through this project, the following concepts were applied practically:

Continuous Integration

Automatically validate changes before they reach the deployment stage.

Continuous Deployment

Automatically deploy successful builds to a cloud environment.

Infrastructure Separation

Separate:

Source Code
    ↓
Build
    ↓
Artifact
    ↓
Deployment Environment

Immutable Application Artifact

Instead of copying source code directly to EC2, the pipeline deploys the built Docker image.

Source Code
     ↓
Docker Build
     ↓
Container Image
     ↓
GHCR
     ↓
EC2

This provides greater consistency between build and deployment environments.


🚧 Future Improvements

The next evolution of this project could introduce:

Infrastructure as Code

Terraform for automated AWS infrastructure provisioning.

HTTPS

AWS Application Load Balancer with TLS certificates.

Monitoring

CloudWatch metrics, logs, and alerts.

Security Scanning

Docker image vulnerability scanning using tools such as Trivy or Docker Scout.

Immutable Versioning

Replace the mutable:

:main

tag with versioned or commit-based tags.

For example:

:v1.0.0

or:

:commit-sha

Automated Rollback

Automatically restore the previous container image if deployment health checks fail.

Deployment Strategies

Introduce:

  • rolling deployments
  • blue/green deployments
  • deployment environments
  • approval gates

Infrastructure Automation

Provision EC2, networking, security groups, and related infrastructure using Terraform.

Container Orchestration

Eventually migrate the application to Kubernetes.


πŸ† Project Outcome

This project progressed from a locally developed FastAPI application to a cloud-hosted, containerized application with an automated CI/CD pipeline.

The final workflow is:

Developer
    ↓
Git
    ↓
GitHub
    ↓
GitHub Actions
    ↓
pytest
    ↓
Docker Build
    ↓
GHCR
    ↓
SSH
    ↓
AWS EC2
    ↓
Docker
    ↓
FastAPI
    ↓
Health Check
    ↓
βœ… Deployment Verified

The key achievement is not simply deploying FastAPI to AWS.

It is demonstrating the ability to design and operate an automated software delivery pipeline connecting source control, testing, containerization, artifact management, cloud infrastructure, deployment automation, and post-deployment verification.


πŸ‘¨β€πŸ’» Author

Paul Iyen

DevOps β€’ Cloud β€’ Cybersecurity

This project is part of a practical DevOps/Cloud engineering portfolio focused on building production-oriented infrastructure, automation, CI/CD pipelines, and cloud deployments.

Repository

cicd-fastapi-aws on GitHub


⭐ Portfolio Summary

CI/CD FastAPI AWS Deployment

Built an end-to-end CI/CD pipeline that automatically tests a FastAPI application, containerizes it with Docker, publishes the image to GitHub Container Registry, and deploys the application to AWS EC2 through SSH, with automated post-deployment health verification.

Core technologies: Python β€’ FastAPI β€’ pytest β€’ Docker β€’ GitHub Actions β€’ GHCR β€’ AWS EC2 β€’ Linux β€’ SSH β€’ Git

About

An end-to-end DevOps project implementing automated testing, Docker containerization, container image publishing, and continuous deployment of a FastAPI application to AWS EC2 using GitHub Actions.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages