Django deployment best practices - production environment deployment and operation and maintenance
📂 Stage: Part 3 - Advanced Topics 🎯 Difficulty Level: Advanced ⏰ Estimated study time: 6-8 hours 🎒 Prerequisite knowledge: 性能优化, 安全最佳实践
Table of contents
Deploy core architecture and principles
Minimalist production architecture
Students who are new to production deployment are easily intimidated by various heavy-duty components - load balancers, automatic scaling, service grids... But in fact, a stable and efficient single-machine architecture can fully support thousands or even tens of thousands of requests per day, and the cost of understanding and maintenance is extremely low.
Let’s start with the most classic Single-machine Docker scalable architecture. The entire structure is clearly layered, and it will be easy to expand horizontally in the future:
- Nginx: Stands at the forefront, handles all client requests, is responsible for HTTPS encryption, static file response, and forwards dynamic requests to the back-end Gunicorn.
- Gunicorn Workers: Where django application code is run, multiple processes process web requests in parallel.
- PostgreSQL: Data persistence, strong passwords and regular backups must be configured in the production environment.
- Redis: lightweight but powerful in-memory data storage, used for caching, session persistence, and message queues.
- Celery (optional): handles time-consuming asynchronous tasks, such as sending emails and generating reports, without blocking user requests.
The biggest advantage of this architecture is that it is simple and easy to maintain, and it can be run with Docker Compose. Later, when it comes to Docker Swarm or Kubernetes, it only requires upgrading the definition file, and the idea is completely smooth.
5 iron rules
In a production environment, there are some bottom lines that must not be broken. Remember these 5 points to help you avoid 90% of big pitfalls:
- Safety first:
DEBUGMust be set toFalse, complex passwords are set for both the database and Redis, and all traffic is forced to go through HTTPS. - High Availability Prototype: Gunicorn multi-Worker + process will automatically restart if it exits unexpectedly to ensure that the service remains online.
- Quick expansion: Currently deployed on a single machine, the architecture design and configuration should allow for horizontal expansion possibilities (such as stateless applications, shared storage and databases).
- Basic monitoring must be in place: log concentration, process survival detection, and basic resource monitoring (CPU, memory, disk) are indispensable.
- Automation and semi-automation combination: First write a Shell script or a command line, and you can manually complete deployment and backup with one click, and then slowly introduce the CI/CD pipeline. Don’t think of full automation right away. :::
Lightweight environment preparation
We assume that you already have a clean Ubuntu 20.04/22.04 server with no Nginx, Python or other web services installed. The following steps can help you quickly build a safe and clean application running environment.
Server initialization script
Directly copy the following script and save it asinit_server.sh,userootThe user can execute it. It only installs the dependencies necessary for the production environment, without extra tools:
:::code-group
A few key points explained:
python3-venv: Used to create a virtual environment.libpq-dev: compilepsycopg2Required to connect to PostgreSQL.supervisor: If you don’t want to rely on Docker’s restart strategy, you can use it to manage the Gunicorn process.- Firewall: Only SSH and Web traffic are allowed to enter, and all other ports are closed.
- Non-root users: From a security perspective, application code should never be executed as root.
Apply environment variable template
Django production configuration is usually injected through environment variables to avoid hardcoding sensitive information in the code. Please create it in your project root directory.envFile (remember Do not submit to Git repository):
:::code-group
:::
production environmentSECRET_KEYIt must be random enough (at least 50 characters, including uppercase and lowercase letters, numbers, and symbols), and cannot be shared with the development environment. you can useopenssl rand -base64 48Generate a strong random value.
Docker Compose full stack deployment
If you want to get your entire application stack running locally or on a server in a matter of minutes, Docker Compose is your best choice. Below we build the containerized deployment of the Django application step by step.
Prepare to apply Dockerfile
This Dockerfile follows best practices such as multi-layer construction and minimum permissions, which can effectively reduce the image size and improve security:
:::code-group
:::
Production environment dependency list
Save the following content asrequirements.txt, use locked versions to avoid unexpected problems caused by dependency upgrades:
:::code-group
:::
Complete Docker Compose configuration
This one belowdocker-compose.ymlMultiple services are defined: PostgreSQL database, Redis cache, web application and Nginx reverse proxy. Through volume mounting and network bridging, they can communicate efficiently:
:::code-group
:::
**Why is it designed like this? **
- web container port mapped to
127.0.0.1: Even if the server's public IP is exposed to port 8000, it cannot be accessed. Only local Nginx can forward it, providing an extra layer of security. - Health Check and Dependency Conditions: Ensure that the database and Redis are ready before starting the web service to avoid errors caused by the startup sequence.
- Volumes: Static files and media files are shared between the web and nginx through named volumes, which are both persistent and isolated.
- Restart strategy
unless-stopped: Unless explicitly stopped, the process will automatically restart if it crashes, basically meeting high availability.
Basic but efficient Nginx configuration
Nginx is the "facade" of the entire request link. Good configuration can greatly improve the response speed and can also block many malicious scans.
Main configuration filenginx.conf
Site virtual host configuration
We will handle HTTP to HTTPS redirection separately, as well as the official service of HTTPS. Please note the replacementyourdomain.comfor your actual domain name.
This configuration is ready for production, but remember to apply for an SSL certificate and put it in the corresponding path (./ssldirectory), otherwise Nginx will fail to start because it cannot find the certificate.
Gunicorn configuration and optimization
Gunicorn is the de facto standard for Python WSGI servers, and configuration files make tuning very easy.
Some suggestions for fine-tuning:
- Number of workers:
CPU核数 × 2 + 1Suitable for most scenarios. If your views are mostly CPU intensive (rare), drop to核数 + 1, to avoid too many context switches. syncvsgevent: For most standard Django applications,syncThe model is simple and reliable; only in scenarios with a large number of third-party API calls or WebSocket do you need to switch to gevent, but you need to install additional dependencies and pay attention to code compatibility.max_requests: Forcing the Worker to restart regularly can effectively prevent memory growth caused by long-term running (even if Python does not have obvious memory leaks, fragments will accumulate).
PostgreSQL Production Security and Backup
The database is the heart of the business, and the production environment must be "stable" and "cannot be lost." In addition to setting a strong password in Docker Compose earlier, we must also configure automatic backup.
Database backup management commands
The following is a backup script that can be called by the django management command. You can also run it as a Python script alone, or even configure it into a Celery scheduled task.
you can passpython manage.py backup_dbRun it manually, or integrate it into the Celery Beat scheduled schedule later (for example, execute it at 3 a.m. every day), and mount the backup directory to the host or cloud storage.
:::tip production tips
- backup directory (
/backups) should be mapped to a path on the host through the volume of Docker Compose, or synchronized to a remote object storage (such as AWS S3) regularly. - Conduct recovery drills regularly to ensure that the backup files are actually usable. :::
Summary of this chapter
Today we have completely walked through the Django stand-alone production environment deployment closed loop, which mainly covers the following links:
- Understand minimalist production architecture: Nginx → Gunicorn → PostgreSQL/Redis, and keep in mind the 5 iron rules.
- Lightweight environment preparation: server initialization, creation of non-root users, firewall configuration, and secure environment variable settings.
- Docker Compose full stack deployment: one
docker-compose.ymlConnect the web, database, cache, and reverse proxy all in series, and have a lot of health checks and automatic restarts. - Nginx and Gunicorn configuration optimization: practical skills such as HTTPS, security headers, static file acceleration, and worker number optimization.
- PostgreSQL automatic backup: Compressed backup and old file cleanup are implemented through django management commands, which is simple and reliable.
:::warning Final checklist before going live
- Apply for and configure a free, auto-renewable Let's Encrypt SSL certificate.
- Close completely
DEBUGand check allALLOWED_HOSTS。 - Modify the default administrator password and set a strong password for the database.
- use
docker compose logsand/health/The endpoint confirms that all services are functioning properly. - If you need more sophisticated process guarding (not relying on Docker restart), you can additionally configure Supervisor.
- Connect to basic monitoring (such as Prometheus + Grafana or simple Uptime Kuma) to have a general understanding of CPU, memory, disk and request error rates. :::
After completing this, your Django application will already have the ability to run stably at the production level. In the future, CI/CD pipelines, horizontal expansion and service splitting can be gradually added on this basis, but the core skeleton is reliable enough to support early business.

