Django deploys nginx+uwsgi+ubuntu (Linux server)

1. Project introduction

In September 2023, I successfully deployed a Django project on Alibaba Cloud. The specific environment is as follows:

  • Server: Ubuntu Server 22.04 LTS 64bit (Linux)
  • Reverse proxy server: Nginx
  • WEB server: uwsgi
  • Project framework: Django (version 4.2)
  • Project running environment: Python3

2. The relationship between nginx, uwsgi and ubuntu

1. First, the request initiated by the user to the server is obtained by nginx.

2. At this time, nginx will make a judgment. If the request is for a static file, it will go directly to the static file directory configured in nginx to obtain the static file; if it is a dynamic request, it will need to forward the request to uwsgi, and then uwsgi will call the application (that is, to Deployed project code) obtains the results and returns them to nginx.

3. Finally, nginx returns the request to the user.

3. Install python, pip, python-Pillow and Django

1. Enter the system and update the source files first and upgrade the existing installation package (not necessary, but recommended)

sudo apt-get update #Update source files and will not perform any installation or upgrade operations
sudo apt-get upgrade #Upgrade all installed packages

2. Install python and pip

#(1) Install python (the latest version will be reinstalled if it is already installed), and verify the version
sudo apt-get install python3
python3 -V #After entering this command line, if the corresponding python version is displayed, it means the installation is successful.

#(2)Install pip
sudo apt-get install python3-pip
pip3 -V #After entering this command line, if the corresponding pip version is displayed, it means the installation is successful.

#(3) Install the Pillow package, otherwise an error will be reported when starting the Django project. If the project has no pictures, don’t worry about it.
python3 -m pip install Pillow #Image processing library

Error message:
erpnav.Product.logo: (fields.E210) Cannot use ImageField because Pillow is not installed.
        HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow".

3. Install and test Django

#(1) Install Django
python3 -m pip install Django

#(2) After installing Django, deploy the project file to the server and run it. You can upload it via ftp or git. See the reference information at the end for git
python3 manage.py runserver #Access the 127.0.0.1:8000 port. If the access is successful, it means that the Django project can run normally. It is recommended to use the W3M browser for access.

#(3) Modify the following two configurations in project settings.py
DEBUG = False #Represents non-development mode
ALLOWED_HOSTS = ["*"] #Allow all requests to access the Django project

#(4) Collect static files to the project/static folder
python3 manage.py collectstatic #After execution, the system’s css, pictures, videos and other files will be included in the project/static folder

4. Install uwsgi and configure it

#(1) Install uwsgi
python3 -m pip install uwsgi #Install, python3 -m pip uninstall uwsgi can be uninstalled

#(2) Configure uwsgi. Add the uwsgi.ini file in the project root directory (for example, the directory /home/ubuntu/saas-time/, built directly in saas-time)
#######################document content######################### #
[uwsgi]
# Directly access the port number of uwsgi, bypassing nginx. You can ignore my configuration and it is of no use.
http=127.0.0.1:8010

# The port number forwarded to nginx, nginx and uwsgi transmit information through this port number
socket=127.0.0.1:8080

# Whether to use the main thread
master=true

#The absolute path of the project, based on your project
chdir=/home/ubuntu/saas-time/

# Relative path to the wsgi.py file of the Django project
wsgi-file = SaasTime/wsgi.py

# Number of processes
processes=4

# Number of threads per process
threads = 2

# Listening port
stats = 127.0.0.1:9191

# Whether to clean up the environment configuration every time you exit
vacuum=true

# Automatically restart once a file in the directory is modified
touch-reload = /home/ubuntu/saas-time

# Store the log****************Important, the core file for troubleshooting uwsgi problems****************
daemonize = /home/ubuntu/saas-time/uWSGI.log

buffer-size = 655365
########################document content######################## ##

#(3) uwsgi operation, at this time you only need to run uwsgi
uwsgi --ini uwsgi.ini #Run uwsgi. At this time, you can ctrl + c to exit the operation (sometimes you can't, I don't understand it yet)
uwsgi --ini uwsgi.ini & amp; #Run uwsgi in the background

###The following command modifies the uwsgi configuration file and needs to be used when restarting###
ps ax|grep uwsgi #View all processes of uwsgi
pkill -f uwsgi -9 #Kill all processes of uwsgi

5. Install Nginx and configure it

#(1) Install and start nginx
sudo apt-get install nginx #Install nginx
sudo /etc/init.d/nginx start #Start nginx, /etc/init.d/ is the file path, which stores the nginx startup script

#(2) Configure the file into the /etc/nginx folder and modify the nginx.conf file to (this file asks for the nginx configuration file. You can use the vim editor to modify it. For usage instructions, see the reference information at the end)
###############**nginx.conf** file content#################
user root; #user www-data; Otherwise nginx does not have permission to access static resource files
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
worker_connections 768;
# multi_accept on;
}

http {

sendfile on;
tcp_nopush on;
types_hash_max_size 2048;


include /etc/nginx/mime.types;
default_type application/octet-stream;


ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;


access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;


gzip on;



include /etc/nginx/conf.d/*.conf;
#include /etc/nginx/sites-enabled/*; #######################This file is the default file for nginx to listen to port 80, please comment it off, otherwise the message will not be forwarded to the uwsgi port configured below when accessing the website.
#######################The following is the added content##############
server {
listen 80 default_server; #Listen to port 80
listen [::]:80 default_server;
server_name 127.0.0.1;
charset utf-8;

client_max_body_size 75M;

location/{
include uwsgi_params;
uwsgi_pass 127.0.0.1:8080; #Forward information to uwsgi on port 8080, which needs to be consistent with the port in the uwsgi.ini configuration file
uwsgi_read_timeout 600;
   uwsgi_send_timeout 600;
    uwsgi_connect_timeout 600;
}
#Request with path /static, obtain static files directly from the static folder in the root directory
location /static {
       alias /home/ubuntu/saas-time/static;
    }
#Requests with the path /media obtain static files directly from the media folder in the root directory (referring to django media files-media)
    location /media {
        alias /home/ubuntu/saas-time/media;
    }
}
}
################document content################

#(2)nginx extension command
sudo nginx -s reload #Reload the configuration without terminating the server. It is recommended to use this command to reload after modifying the configuration file.
sudo systemctl restart nginx #restart
sudo nginx -s quit
nginx {start|stop|restart|reload|force-reload|status|configtest|rotate|upgrade}

6. Turn on the firewall and access the system

Servers purchased from cloud service vendors have firewall configurations. Remember to open access to port 80. After opening, you can use the IP address to access. If the project content is displayed normally, it means the configuration is successful. Otherwise, the problem needs to be checked.

Under the premise that nginx and uwsgi are running and the firewall is turned on, please find the log files of nginx and uwsgi. nginx will definitely generate logs every time you visit the website. Uwsgi depends on the situation. Please use the log information to troubleshoot the problem.

  • uwsgi log: specified by the daemonize configuration item in the uwsgi.ini file
  • nginx log: access_log and error_log configuration items specified in nginx.conf file

7. Important reference information

1. The difference between Django static files (static) and media files (media), and the definition of nginx static files

2. Simple use of git (code warehouse code cloud/github)