β CI/CD for FastAPI with GitHub Actions and Docker (Self-Hosted Deployment)
this instruction was generated by Chat-GPT-4O
π Project Structure (Example)
1 | /my-project |
π³ 1. FastAPI Dockerfile Example (backend/Dockerfile)
1 | FROM python:3.11-slim |
βοΈ 2. GitHub Actions Workflow (.github/workflows/deploy-backend.yml)
1 | name: Deploy FastAPI Backend |
π 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 | ssh-keygen -t rsa -b 4096 -C "ci-cd-key" |
π 4. Deployment Process Summary
On
git pushtomain, GitHub Actions:- Syncs
backend/files to your computer viarsync + SSH. - Connects via SSH and rebuilds the FastAPI Docker image.
- Restarts the container.
- Syncs
π§ͺ (Optional) Improve With:
.dockerignoreto avoid copying unnecessary files.- Add
tests/and runpytestbefore deployment. - Use
docker-composeif 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?