Deploy a Django project with Nginx and uWSGI

Updated at:

Use Nginx to serve static files and uWSGI to handle Django application processes on an ECS instance.

How it works

image
  1. The browser sends an HTTP or HTTPS request to the server.

  2. 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.

  3. uWSGI passes the request to the Django application and provides load balancing.

  4. 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_id to the instance ID, then click Start Debugging > Plan & Apply.

  • To create a new instance, leave ecs_instance_id empty, then click Start Debugging > Plan & Apply.

Procedure

Step 1: Prepare resources

  1. Create a Virtual Private Cloud (VPC) and a vSwitch.

  2. Create an ECS instance.

    1. Go to the instance purchase page. Select the Custom Launch tab.

    2. Instance type: At least 2 vCPUs and 4 GiB of memory.

    3. Image: Alibaba Cloud Linux 3.

    4. 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).

  3. Configure the runtime environment.

    1. Log on to a Linux instance by using Workbench.

    2. 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
    3. Create the logs, static, and media directories and the /run/uwsgi directory for the socket file.

      sudo mkdir -p /srv/django-app/{logs,static,media}
      sudo mkdir -p /run/uwsgi

Step 2: Deploy the Django application

  1. 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/
  2. Modify /srv/django-app/myproject/settings.py for production use.

    • Set DEBUG to False to avoid exposing sensitive information.

    • Set ALLOWED_HOSTS to 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.

  3. Collect static files into STATIC_ROOT for Nginx to serve directly.

    sudo python3.8 /srv/django-app/manage.py collectstatic --noinput
  4. Run database migrations to initialize the database schema.

    Django defaults to SQLite3, which is not suitable for production. Replace it by modifying DATABASES in myproject/settings.py.
    sudo python3.8 /srv/django-app/manage.py migrate
  5. Create an administrator account for the Django admin panel.

    sudo python3.8 /srv/django-app/manage.py createsuperuser

Step 3: Configure the uWSGI service

  1. Create the uWSGI configuration file /etc/django-app.ini.

    Set processes based 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
  2. Start uWSGI in the background.

    Check uWSGI process status: ps aux | grep uwsgi.
    nohup /usr/local/bin/uwsgi --ini /etc/django-app.ini &
  3. (Optional) Manage uWSGI with systemd for automatic startup and recovery.

    1. 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
    2. Start the uWSGI service and enable it on boot.

      sudo systemctl daemon-reload
      sudo systemctl start uwsgi-django-app
      sudo systemctl enable uwsgi-django-app

      Check the service status.

      sudo systemctl status uwsgi-django-app

Step 4: Configure Nginx as a frontend server

  1. 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;
        }
    }
  2. Run nginx -t to verify the configuration syntax.

    Output with syntax is ok and test is successful confirms valid configuration.

  3. Restart Nginx and enable it on boot.

    sudo systemctl restart nginx
    sudo systemctl enable nginx
  4. Open http://<your_ECS_instance_public_IP_address>/admin to 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 nginx on 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.

  1. Temporarily set DEBUG to True in settings.py, restart uWSGI, and refresh the page. The browser displays a stack trace that pinpoints the issue.

    Important

    Only enable debug mode for troubleshooting. Set DEBUG back to False afterward to prevent exposing sensitive information.

  2. Check the uWSGI log file for the specific Django error.