16. CI/CD Essentials

Automate checks and deployments; ship small changes safely with fast rollback.

Question: What are the key characteristics of a good Dockerfile for a Python application?

Answer: A good Dockerfile produces a small, secure, and efficient image. Key practices include:

  1. Using multi-stage builds: To separate build-time dependencies from the final, minimal runtime image.

  2. Using a slim base image: E.g., python:3.11-slim.

  3. Optimizing layer caching: By copying pyproject.toml and installing dependencies before copying the application source code.

  4. Running as a non-root user: A critical security measure to reduce container privileges.

  5. Including healthchecks: To inform the orchestrator (like Kubernetes) about the application's status.

# syntax=docker/dockerfile:1.6
FROM python:3.11-slim AS base
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
RUN pip install --no-cache-dir --upgrade pip
COPY pyproject.toml .
RUN pip install --no-cache-dir .
COPY . .
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8080"]

Question: What stages should a robust CI/CD pipeline include?

Answer: Lint/format, type-check, unit tests, security scans (SCA/SAST), build artifacts (wheels/images), SBOM generation, integration/e2e tests, deploy with migration gates, and automated rollback.

Explanation: Fail fast and shift-left to catch issues early; use ephemeral environments.