CI/CD for FastAPI with GitHub Actions and Docker (Self-Hosted Deployment)

βœ… CI/CD for FastAPI with GitHub Actions and Docker (Self-Hosted Deployment)

this instruction was generated by Chat-GPT-4O

πŸ“ Project Structure (Example)

1
2
3
4
5
6
7
8
9
/my-project
β”œβ”€β”€ frontend/ # Your Next.js app (deployed via Vercel)
β”œβ”€β”€ backend/ # Your FastAPI app
β”‚ β”œβ”€β”€ Dockerfile
β”‚ β”œβ”€β”€ app/
β”‚ └── requirements.txt
└── .github/
└── workflows/
└── deploy-backend.yml

🐳 1. FastAPI Dockerfile Example (backend/Dockerfile)

1
2
3
4
5
6
7
8
9
10
FROM python:3.11-slim

WORKDIR /app

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

COPY ./app /app

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

βš™οΈ 2. GitHub Actions Workflow (.github/workflows/deploy-backend.yml)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
name: Deploy FastAPI Backend

on:
push:
paths:
- 'backend/**'
branches: [main]

jobs:
deploy:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up SSH
uses: webfactory/ssh-agent@v0.9.0
with:
ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}

- name: Copy backend files to server
run: |
rsync -avz -e "ssh -o StrictHostKeyChecking=no" backend/ ${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }}:/home/${{ secrets.SERVER_USER }}/fastapi-app/

- name: SSH and rebuild Docker container
run: |
ssh -o StrictHostKeyChecking=no ${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }} << 'EOF'
cd ~/fastapi-app
docker stop fastapi-app || true
docker rm fastapi-app || true
docker build -t fastapi-app .
docker run -d --name fastapi-app -p 8000:8000 fastapi-app
EOF

πŸ” 3. GitHub Secrets Required

Go to your GitHub repo β†’ Settings β†’ Secrets β†’ Actions β†’ New repository secret:

Name Description
SSH_PRIVATE_KEY Your local server’s SSH private key (for GitHub to connect)
SERVER_USER Your username on the server/computer
SERVER_HOST IP or hostname of your computer

You can generate a key pair via:

1
2
ssh-keygen -t rsa -b 4096 -C "ci-cd-key"
# Add the public key (~/.ssh/id_rsa.pub) to ~/.ssh/authorized_keys on your computer

πŸš€ 4. Deployment Process Summary

  1. On git push to main, GitHub Actions:

    • Syncs backend/ files to your computer via rsync + SSH.
    • Connects via SSH and rebuilds the FastAPI Docker image.
    • Restarts the container.

πŸ§ͺ (Optional) Improve With:

  • .dockerignore to avoid copying unnecessary files.
  • Add tests/ and run pytest before deployment.
  • Use docker-compose if you also run a database or Redis locally.
  • Watchdog tools like Watchtower to auto-update containers on image changes.

Would you like a template for a docker-compose.yml setup too, in case your FastAPI app depends on other services like PostgreSQL or Redis?