Saltar al contenido
Web Development

CI/CD for Django: GitHub Actions, Docker, and Zero-Downtime Deploys

Ruslan Danelian 7 min de lectura
¡Copiado!
CI/CD for Django: GitHub Actions, Docker, and Zero-Downtime Deploys

Manual deployments work until the day they do not: someone forgets to run migrations, a dependency differs between laptop and server, or a Friday-afternoon deploy takes the site down for twenty minutes. A CI/CD pipeline replaces that ritual with a repeatable process: every change is linted, tested, built into an image, and deployed the same way, with no visible downtime. This guide builds that pipeline for Django using GitHub Actions and Docker.

If you currently deploy to a VPS the traditional way, our guide to Django deployment with Gunicorn, Nginx and systemd is the baseline this article improves on.

Key Takeaways
  • The pipeline at a glance
  • GitHub Actions workflow
  • Environment management
  • Monitoring after deploy

The pipeline at a glance

  1. Lint with ruff for style and common bugs.
  2. Test with pytest against a real PostgreSQL service container.
  3. Build a Docker image and push it to a registry.
  4. Deploy the new image to staging, run smoke tests, then promote to production.
  5. Verify health checks and roll back automatically on failure.

Docker setup

🧭 Illustration: step-by-step process diagram for Docker setup
Visual guide: Docker setup

Multi-stage Dockerfile

A multi-stage build keeps production images small and free of build tools.

FROM python:3.12-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt

FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
WORKDIR /app
COPY --from=builder /wheels /wheels
RUN pip install --no-cache-dir /wheels/* && rm -rf /wheels
COPY . .
RUN python manage.py collectstatic --noinput
RUN useradd -m app && chown -R app /app
USER app
CMD ["gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8000", "--workers", "3"]

docker-compose for local development

Compose gives every developer the same stack: the Django app with code mounted as a volume, PostgreSQL, and Redis. New team members run docker compose up and are productive in minutes instead of days.

Compose gives every developer the same stack: the Django app with code mounted as a volume, PostgreSQL, and Redis.

GitHub Actions workflow

name: ci
on:
  push:
    branches: [main]
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env: {POSTGRES_PASSWORD: postgres}
        ports: ["5432:5432"]
        options: >-
          --health-cmd pg_isready --health-interval 5s
          --health-timeout 5s --health-retries 10
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: {python-version: "3.12", cache: pip}
      - run: pip install -r requirements.txt
      - run: ruff check . && ruff format --check .
      - run: pytest -q
        env:
          DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres

  build-deploy:
    needs: test
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: docker/build-push-action@v5
        with:
          push: true
          tags: ghcr.io/${{ github.repository }}:${{ github.sha }}
      - run: ./scripts/deploy.sh ${{ github.sha }}
        env:
          SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}

Tag images with the commit SHA rather than only latest. That makes every deploy traceable and every rollback a one-line change.

Pro Tip

When working on GitHub Actions workflow, pick one measurable goal first, track it weekly, and only scale what the data shows is working.

Zero-downtime deployment strategies

StrategyHow it worksDowntimeRollback speedComplexity
Rolling updateReplace instances one at a time behind a load balancerNoneMinutesLow to medium
Blue-greenRun old and new stacks side by side, switch traffic at the proxyNoneSecondsMedium
CanarySend a small percentage of traffic to the new version firstNoneSecondsHigh
Recreate (stop/start)Stop old, start newSeconds to minutesMinutesVery low

For a single VPS, blue-green with Nginx is the most practical: start the new container on a second port, wait for its health check, reload Nginx to point at it, then stop the old container.

The migration problem

Zero downtime breaks if migrations are not backward-compatible. During a rollout, old and new code run against the same database. Follow expand and contract: first deploy additive changes (new nullable columns), then deploy code that uses them, and only later remove old columns in a separate release. Run migrate as a separate step before switching traffic.

Want expert help with this? Let's make it happen.

Get a Free Consultation

Environment management

🎯 Illustration: diagram illustrating Environment management
Visual guide: Environment management
  • Development: docker-compose, debug on, console email.
  • Staging: production-like settings, a copy of anonymized data, auto-deployed from main.
  • Production: promoted from staging with manual approval, or automatic for low-risk apps.

Use split settings modules and read all configuration from environment variables. Keep the image identical across environments; only variables change.

Secret management

💡 Illustration: conceptual illustration of Secret management
Visual guide: Secret management

Store secrets in GitHub encrypted secrets or your cloud provider's secret manager, never in the repository or the image. Use separate secrets per environment, rotate on a schedule, and give the deploy key access to the deploy user only.

Monitoring after deploy

A deploy is not done until it is verified. Add a /health/ endpoint that checks the database and cache, run it automatically after the switch, and roll back if it fails. Track error rates with Sentry, uptime with an external monitor, and response times on key endpoints. Pair this with the performance work in our guide to Django site speed optimization, and consider putting Cloudflare Workers in front of Django for caching and edge logic. If you would like a pipeline designed and implemented for your project, see our infrastructure and DevOps service.

Related reading: Django Deployment with Gunicorn, Nginx and systemd on a VPS | Cloudflare Workers and Django: Edge Computing | Django Site Speed Optimization

Want a deployment pipeline you never have to think about? Explore my infrastructure and DevOps service or get in touch for a free consultation.

CI/CD for Django: GitHub Actions, Docker, and Zero-Downtime Deploys infographic (English version)
CI/CD for Django: GitHub Actions, Docker, and Zero-Downtime Deploys infographic (versión en español)
CI/CD for Django: GitHub Actions, Docker, and Zero-Downtime Deploys infographic (версия на русском)
📌 Save this infographic for quick reference

Frequently Asked Questions

Do I need Docker to use CI/CD with Django?

No. You can run tests and deploy over SSH without containers. Docker adds consistency between environments and makes rollbacks simpler, which is why it is worth adopting for most production apps.

How do I handle database migrations with zero downtime?

Make migrations backward-compatible using the expand and contract pattern: add new columns first, deploy code that uses them, then remove old columns in a later release. Run migrations before switching traffic.

What is the cheapest way to get zero-downtime deploys?

Blue-green on a single VPS with Nginx. Start the new container on another port, health check it, reload Nginx to switch, and stop the old container. It requires no orchestration platform.

Ruslan Danelian
Ruslan Danelian

Desarrollador full-stack especializado en Django, automatización con IA y gestión de Google Ads. Construyo plataformas SaaS de producción y aplicaciones web personalizadas para empresas en todo EE.UU.

Lea a continuación

¿Tiene un proyecto en mente?

Cuénteme qué necesita. En un plazo de un día hábil le enviaré un plan con cronograma y precio fijo.

Year-end offer

20% off AI tools & custom CRM

AI chat assistants, DM bots, lead scoring and a CRM built around your business.

Claim 20% off