Python FastAPI Tutorial (Part 19): Deploy with Docker - Serverless Containers and Custom Domain
TL;DR
This tutorial demonstrates how to deploy a FastAPI application to Google Cloud Run using Docker containers, implementing security headers via middleware, leveraging multi-stage builds with the UV package manager for optimization, and configuring the container for serverless deployment with proper signal handling and non-root user privileges.
☁️ Cloud Deployment Architecture 3 insights
Serverless infrastructure management
Google Cloud Run handles automatic scaling, managed SSL certificates, and scale-to-zero functionality, eliminating the need to manage operating systems or Nginx configurations.
Managed database solution
Neon provides a fully managed PostgreSQL service that removes the burden of database server maintenance and security updates.
Cost-efficient scaling model
The application scales down to zero when idle, ensuring you only pay for actual usage rather than maintaining constantly running servers.
🔒 Application Security 3 insights
Middleware-based security headers
FastAPI middleware adds X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Strict-Transport-Security directly in application code since Cloud Run lacks Nginx.
Health check endpoint
A database connectivity check performs 'SELECT 1' queries to verify application status for load balancers and monitoring systems.
Non-root container execution
The Dockerfile creates and runs as an 'appuser' with limited privileges to minimize security risks if the application is compromised.
🐳 Docker Build Optimization 3 insights
Multi-stage build process
The Dockerfile uses a builder stage to compile dependencies with UV, then discards it to create a minimal production image containing only the virtual environment and application code.
UV package manager integration
Using UV instead of pip with bytecode compilation and copy link mode enables faster, more reliable builds while ensuring Python uses the base image interpreter.
Layer caching strategy
Copying pyproject.toml and uv.lock before application code leverages Docker layer caching to avoid reinstalling dependencies when only source code changes.
⚙️ Production Configuration 3 insights
Proper signal handling with exec
The container command uses 'exec' to replace the shell process, ensuring Cloud Run shutdown signals reach the FastAPI application for graceful termination.
Immediate log output
Setting PYTHONUNBUFFERED=1 forces Python to flush output immediately, preventing delayed logs in Cloud Run's viewer during debugging.
Version pinning for reproducibility
Pinning exact versions like Python 3.14.4 and specific UV releases ensures builds remain consistent and won't break from upstream image updates.
Bottom Line
Package your FastAPI app in a multi-stage Docker container using UV for dependency management, implement security headers directly in application middleware rather than relying on reverse proxies, and deploy to Google Cloud Run for automatic scaling and zero server maintenance.
More from Corey Schafer
View all
Python FastAPI Tutorial (Part 18): Deploy to a VPS - Security, Nginx, SSL, and Custom Domain
Corey Schafer demonstrates how to deploy a production-ready FastAPI application to a Virtual Private Server (VPS), emphasizing fundamental deployment concepts including security hardening, SSH key authentication, and health check implementation before moving to managed cloud solutions.
Python FastAPI Tutorial (Part 17): Testing the API - Pytest, Fixtures, and Mocking External Services
This tutorial demonstrates how to implement comprehensive testing for FastAPI applications using pytest with async support, covering critical setup patterns like environment variable configuration before app imports, using AsyncClient for async endpoints, mocking AWS S3 with Moto, and maintaining a separate PostgreSQL test database to ensure production parity.
Python FastAPI Tutorial (Part 16): AWS S3 and Boto3 - Moving File Uploads to the Cloud
This tutorial demonstrates how to migrate a FastAPI application from local disk storage to AWS S3 for production file uploads, covering S3 bucket setup, IAM security configuration, and Boto3 integration while maintaining separation between image processing and storage layers.
Python FastAPI Tutorial (Part 15): PostgreSQL and Alembic - Database Migrations for Production
This tutorial transitions a FastAPI application from SQLite to PostgreSQL for production readiness, implementing Alembic for database migrations to enable safe, version-controlled schema changes without data loss.