Deploy a Django project with Nginx and uWSGI
Use Nginx to serve static files and uWSGI to handle Django application processes on an ECS instance.
How it works
-
The browser sends an HTTP or HTTPS request to the server.
-
Nginx receives the request as the frontend server.
-
For static files (CSS, JavaScript, images), Nginx serves them directly, reducing Django's load.
-
Dynamic requests are forwarded to the uWSGI server.
-
-
uWSGI passes the request to the Django application and provides load balancing.
-
The Django application handles the business logic (such as querying a database or rendering a template) and returns a response to uWSGI.
Quick deployment
Terraform can deploy this solution with a single click on an existing or new instance.
-
To deploy to an existing instance, set
ecs_instance_idto the instance ID, then click . -
To create a new instance, leave ecs_instance_id empty, then click .
Procedure
Step 1: Prepare resources
-
Create an ECS instance.
-
Go to the instance purchase page. Select the Custom Launch tab.
-
Instance type: At least 2 vCPUs and 4 GiB of memory.
-
Image: Alibaba Cloud Linux 3.
-
Network and Security Group:
-
Network: Select the VPC you created.
-
Public IP: Select Assign Public IPv4 Address.
-
Security group: Select Create Security Group and select HTTP (TCP: 80).
-
-
-
Configure the runtime environment.
-
Install Nginx and Python development tools for compiling uWSGI.
The default Nginx version is outdated. Add the official Nginx repository for the latest stable version.
# Add the official Nginx source to the system. sudo tee /etc/yum.repos.d/nginx.repo <<-'EOF' [nginx-stable] name=nginx stable repo baseurl=http://nginx.org/packages/centos/8/$basearch/ gpgcheck=1 enabled=1 gpgkey=https://nginx.org/keys/nginx_signing.key module_hotfixes=true EOF sudo yum install -y python3.8 python38-devel pcre-devel gcc make nginx # Install Django and uWSGI. sudo python3.8 -m pip install --upgrade pip wheel -i https://mirrors.aliyun.com/pypi/simple sudo python3.8 -m pip install "Django>=4.2,<5.0" "uwsgi>=2.0.23" -i https://mirrors.aliyun.com/pypi/simple -
Create the
logs,static, andmediadirectories and the/run/uwsgidirectory for the socket file.sudo mkdir -p /srv/django-app/{logs,static,media} sudo mkdir -p /run/uwsgi
Step 2: Deploy the Django application
-
Create a sample Django project.
Use a Python virtual environment to isolate dependencies and avoid version conflicts.
sudo /usr/local/bin/django-admin startproject myproject /srv/django-app/ -
Modify
/srv/django-app/myproject/settings.pyfor production use.-
Set
DEBUGtoFalseto avoid exposing sensitive information. -
Set
ALLOWED_HOSTSto the public IP address of your instance. Django refuses to start if this list is empty.The IP address must be a string, for example,
['xxx.xxx.xxx.xxx'] -
Add
STATIC_ROOT = BASE_DIR / 'static'to the end of the file.
-
-
Collect static files into
STATIC_ROOTfor Nginx to serve directly.sudo python3.8 /srv/django-app/manage.py collectstatic --noinput -
Run database migrations to initialize the database schema.
Django defaults to SQLite3, which is not suitable for production. Replace it by modifying
DATABASESinmyproject/settings.py.sudo python3.8 /srv/django-app/manage.py migrate -
Create an administrator account for the Django admin panel.
sudo python3.8 /srv/django-app/manage.py createsuperuser
Step 3: Configure the uWSGI service
-
Create the uWSGI configuration file
/etc/django-app.ini.Set
processesbased on CPU cores. Recommended:Number of Cores * 2.Run the service as a non-privileged user to prevent root access if the application is compromised.
[uwsgi] # Project configuration chdir = /srv/django-app module = myproject.wsgi:application # Process configuration master = true processes = 4 threads = 2 # Network and permission configuration socket = /run/uwsgi/django-app.sock chmod-socket = 666 chown-socket = root:root vacuum = true # Security and runtime configuration uid = root gid = root die-on-term = true # Log configuration logto = /srv/django-app/logs/uwsgi.log -
Start uWSGI in the background.
Check uWSGI process status:
ps aux | grep uwsgi.nohup /usr/local/bin/uwsgi --ini /etc/django-app.ini & -
(Optional) Manage uWSGI with systemd for automatic startup and recovery.
-
Create a startup file:
/etc/systemd/system/uwsgi-django-app.service, with the following script.[Unit] Description=uWSGI service for Django App After=network.target [Service] User=root Group=root RuntimeDirectory=uwsgi ExecStart=/usr/local/bin/uwsgi --ini /etc/django-app.ini Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target -
Start the uWSGI service and enable it on boot.
sudo systemctl daemon-reload sudo systemctl start uwsgi-django-app sudo systemctl enable uwsgi-django-appCheck the service status.
sudo systemctl status uwsgi-django-app
-
Step 4: Configure Nginx as a frontend server
-
Replace
<server_ip>with your instance's public IP address and save the file as/etc/nginx/conf.d/django-app.conf.# Define an upstream that points to the uWSGI socket file. upstream django_backend { server unix:/run/uwsgi/django-app.sock; } server { listen 80; server_name <server_ip>; # Replace with the public IP address. charset utf-8; client_max_body_size 20M; # Static file service location /static/ { alias /srv/django-app/static/; } # Media file service location /media/ { alias /srv/django-app/media/; } # Proxy all other requests to the Django application. location / { include /etc/nginx/uwsgi_params; uwsgi_pass django_backend; } } -
Run
nginx -tto verify the configuration syntax.Output with
syntax is okandtest is successfulconfirms valid configuration. -
Restart Nginx and enable it on boot.
sudo systemctl restart nginx sudo systemctl enable nginx -
Open
http://<your_ECS_instance_public_IP_address>/adminto access the Django admin panel.
Apply in production
-
Run the service as a non-privileged user: Create a system user with no login shell. This limits the blast radius if the application is compromised.
# Create a system user (django-app) with no logon permissions. sudo useradd --system --shell /bin/false --home /srv/django-app django-app # Change the ownership of the application directory to the django-app user. sudo chown -R django-app:django-app /srv/django-app -
Use a Python virtual environment: Isolate each project's dependencies to prevent version conflicts.
# Create a virtual environment. python3.8 -m venv venv # Activate the virtual environment. source venv/bin/activate
Troubleshooting
502 Bad Gateway error
Nginx cannot communicate with uWSGI.
-
Check the uWSGI service status:
systemctl status uwsgi-django-app. -
View the uWSGI logs:
tail -f /srv/django-app/logs/uwsgi.log. -
Check if the socket file exists and verify its permissions:
ls -l /run/uwsgi/django-app.sock.
403 Forbidden error when accessing static files
The Nginx process lacks permission to read the static files directory.
-
Verify that the Nginx user (typically
nginxon Alibaba Cloud Linux) has read (r) and execute (x) permissions on/srv/django-app/static/and its subdirectories.
500 Internal server error
An internal error occurred in the Django application.
-
Temporarily set
DEBUGtoTrueinsettings.py, restart uWSGI, and refresh the page. The browser displays a stack trace that pinpoints the issue.ImportantOnly enable debug mode for troubleshooting. Set
DEBUGback toFalseafterward to prevent exposing sensitive information. -
Check the uWSGI log file for the specific Django error.