search
HomeOperation and MaintenanceNginxHow to deploy Django through Nginx based on ubuntu

1. Install nginx Nginx is a lightweight web server/reverse proxy server and email (imap/pop3) proxy server , and released under a bsd-like license. Its characteristics are that it occupies less memory and has strong concurrency capabilities. In fact, nginx's concurrency capabilities do perform better among web servers of the same type.

nginx is also a very popular web server. We will also give a brief introduction here to use it to deploy django.

nginx official website:

Open the ubuntu console (ctrl alt t) and use the ubuntu warehouse to install.

fnngj@ubuntu:~$ sudo apt-get install nginx #安装

Start nginx:

fnngj@ubuntu:~$ /etc/init.d/nginx start #启动
fnngj@ubuntu:~$ /etc/init.d/nginx stop #关闭
fnngj@ubuntu:~$ /etc/init.d/nginx restart #重启

Modify the nginx default port number, open the /etc/nginx/nginx.conf file, and modify the port number.

 server {
  listen    8088;  # 修改端口号
  server_name localhost;

  #charset koi8-r; 

  #access_log logs/host.access.log main;

  location / {
    root  html;
    index index.html index.htm;
  }

Approximately at line 36 of the file, change the default port number 80 to another port number, such as 8088. Because the default port number 80 is easily occupied by other applications.

Then, restart nginx through the above command. Visit: http://127.0.0.1:8088/

 

How to deploy Django through Nginx based on ubuntuIf the above picture appears, it means nginx started successfully.

2. Install uwsgi

Install uwsgi through pip.

root@ubuntu:/etc# python3 -m pip install uwsgi
Test uwsgi, create the test.py file:
def application(env, start_response):
  start_response('200 ok', [('content-type','text/html')])
  return [b"hello world"]

Run the file through uwsgi.

fnngj@ubuntu:~/pydj$ uwsgi --http :8001 --wsgi-file test.py

Next configure the connection between django and uwsgi. Here, the assumed location of my django project is: /home/fnngj/pydj/myweb

Copy code The code is as follows:How to deploy Django through Nginx based on ubuntu

uwsgi --http :8001 --chdir / home/fnngj/pydj/myweb/ --wsgi-file myweb/wsgi.py --master --processes 4 --threads 2 --stats 127.0.0.1:9191

Commonly used Options:

http: Protocol type and port number

processes: Number of processes started

workers: Number of processes started, equivalent to processes (according to the official website) is spawn the specified number of workers / processes)

chdir: Specify the running directory (chdir to specified directory before apps loading)

wsgi-file: Load wsgi-file (load .wsgi file)

stats: Enable the stats server on the specified address.

threads: Run threads. Due to the existence of gil, I think this is really useless. (run each worker in prethreaded mode with the specified number of threads)

master: Allow the master process to exist (enable master process)

daemonize: Make the process run in the background and log to Specified log file or udp server (daemonize uwsgi). In fact, the most commonly used method is to output the running records to a local file.

pidfile: Specify the location of the pid file and record the pid number of the main process.

vacuum: Automatically clean up the environment when the server exits, delete the unix socket file and pid file (try to remove all of the generated file/sockets)

3. nginx uwsgi django

                                                                                                                                                                                                                                                                                       

Next, we have to combine the three. First, list the files required for the project:

myweb/

├── manage.py

├── myweb/

│  ├── __init__.py

│  ├── settings.py

│  ├── urls.py

│  └── wsgi.py

└── myweb_uwsgi.ini
When we created the myweb project through django, the wsgi.py file was generated for us in the subdirectory myweb. Therefore, we only need to create the myweb_uwsgi.ini configuration file. Of course, uwsgi supports multiple types of configuration files, such as xml, ini, etc. Here, use ini type configuration.
# myweb_uwsgi.ini file
[uwsgi]

# django-related settings

socket = :8000

# the base directory (full path)
chdir      = /home/fnngj/pydj/myweb

# django s wsgi file
module     = myweb.wsgi

# process-related settings
# master
master     = true

# maximum number of worker processes
processes    = 4

# ... with appropriate permissions - may be needed
# chmod-socket  = 664
# clear environment on exit
vacuum     = true

This configuration is actually equivalent to documenting it through the wsgi command followed by a bunch of parameters in the previous section.

socket Specifies the port number for project execution.

chdir specifies the directory of the project.

module myweb.wsgi can be understood in this way. For the myweb_uwsgi.ini file, there is a myweb directory at the same level as it, and there is a wsgi.py file in this directory.

For other parameters, please refer to the introduction of parameters in the previous section.

接下来,切换到myweb项目目录下,通过uwsgi命令读取myweb_uwsgi.ini文件启动项目。

fnngj@ubuntu:~$ cd /home/fnngj/pydj/myweb/
fnngj@ubuntu:~/pydj/myweb$ uwsgi --ini myweb_uwsgi.ini 
[uwsgi] getting ini configuration from myweb_uwsgi.ini
*** starting uwsgi 2.0.12 (32bit) on [sat mar 12 13:05:06 2016] ***
compiled with version: 4.8.4 on 26 january 2016 06:14:41
os: linux-3.19.0-25-generic #26~14.04.1-ubuntu smp fri jul 24 21:18:00 utc 2015
nodename: ubuntu
machine: i686
clock source: unix
detected number of cpu cores: 2
current working directory: /home/fnngj/pydj/myweb
detected binary path: /usr/local/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
chdir() to /home/fnngj/pydj/myweb
your processes number limit is 15962
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to tcp address :8000 fd 3
python version: 3.4.3 (default, oct 14 2015, 20:37:06) [gcc 4.8.4]
*** python threads support is disabled. you can enable it with --enable-threads ***
python main interpreter initialized at 0x8b52dc0
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 319920 bytes (312 kb) for 4 cores
*** operational mode: preforking ***
wsgi app 0 (mountpoint='') ready in 1 seconds on interpreter 0x8b52dc0 pid: 7158 (default app)
*** uwsgi is running in multiple interpreter mode ***
spawned uwsgi master process (pid: 7158)
spawned uwsgi worker 1 (pid: 7160, cores: 1)
spawned uwsgi worker 2 (pid: 7161, cores: 1)
spawned uwsgi worker 3 (pid: 7162, cores: 1)
spawned uwsgi worker 4 (pid: 7163, cores: 1)

注意查看uwsgi的启动信息,如果有错,就要检查配置文件的参数是否设置有误。

再接下来要做的就是修改nginx.conf配置文件。打开/etc/nginx/nginx.conf文件,添加如下内容。

……
server {
  listen     8099; 
  server_name  127.0.0.1 
  charset utf-8;
  access_log   /var/log/nginx/myweb_access.log;
  error_log    /var/log/nginx/myweb_error.log;

  client_max_body_size 75m;

  location / { 
    include uwsgi_params;
    uwsgi_pass 127.0.0.1:8000;
    uwsgi_read_timeout 2;
  }  
  location /static {
    expires 30d;
    autoindex on; 
    add_header cache-control private;
    alias /home/fnngj/pydj/myweb/static/;
   }
 }
……

 listen 指定的是nginx代理uwsgi对外的端口号。

server_name  网上大多资料都是设置的一个网址(例,www.example.com),我这里如果设置成网址无法访问,所以,指定的到了本机默认ip。

在进行配置的时候,我有个问题一直想不通。nginx到底是如何uwsgi产生关联。现在看来大概最主要的就是这两行配置。

include uwsgi_params;

uwsgi_pass 127.0.0.1:8000;

include 必须指定为uwsgi_params;而uwsgi_pass指的本机ip的端口与myweb_uwsgi.ini配置文件中的必须一直。

现在重新启动nginx,翻看上面重启动nginx的命令。然后,访问:http://127.0.0.1:8099/

通过这个ip和端口号的指向,请求应该是先到nginx的。如果你在页面上执行一些请求,就会看到,这些请求最终会转到uwsgi来处理。

How to deploy Django through Nginx based on ubuntu

The above is the detailed content of How to deploy Django through Nginx based on ubuntu. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
NGINX Unit: Supporting Different Programming LanguagesNGINX Unit: Supporting Different Programming LanguagesApr 16, 2025 am 12:15 AM

NGINXUnit supports multiple programming languages ​​and is implemented through modular design. 1. Loading language module: Load the corresponding module according to the configuration file. 2. Application startup: Execute application code when the calling language runs. 3. Request processing: forward the request to the application instance. 4. Response return: Return the processed response to the client.

Choosing Between NGINX and Apache: The Right Fit for Your NeedsChoosing Between NGINX and Apache: The Right Fit for Your NeedsApr 15, 2025 am 12:04 AM

NGINX and Apache have their own advantages and disadvantages and are suitable for different scenarios. 1.NGINX is suitable for high concurrency and low resource consumption scenarios. 2. Apache is suitable for scenarios where complex configurations and rich modules are required. By comparing their core features, performance differences, and best practices, you can help you choose the server software that best suits your needs.

How to start nginxHow to start nginxApr 14, 2025 pm 01:06 PM

Question: How to start Nginx? Answer: Install Nginx Startup Nginx Verification Nginx Is Nginx Started Explore other startup options Automatically start Nginx

How to check whether nginx is startedHow to check whether nginx is startedApr 14, 2025 pm 01:03 PM

How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

How to close nginxHow to close nginxApr 14, 2025 pm 01:00 PM

To shut down the Nginx service, follow these steps: Determine the installation type: Red Hat/CentOS (systemctl status nginx) or Debian/Ubuntu (service nginx status) Stop the service: Red Hat/CentOS (systemctl stop nginx) or Debian/Ubuntu (service nginx stop) Disable automatic startup (optional): Red Hat/CentOS (systemctl disabled nginx) or Debian/Ubuntu (syst

How to configure nginx in WindowsHow to configure nginx in WindowsApr 14, 2025 pm 12:57 PM

How to configure Nginx in Windows? Install Nginx and create a virtual host configuration. Modify the main configuration file and include the virtual host configuration. Start or reload Nginx. Test the configuration and view the website. Selectively enable SSL and configure SSL certificates. Selectively set the firewall to allow port 80 and 443 traffic.

How to solve nginx403 errorHow to solve nginx403 errorApr 14, 2025 pm 12:54 PM

The server does not have permission to access the requested resource, resulting in a nginx 403 error. Solutions include: Check file permissions. Check the .htaccess configuration. Check nginx configuration. Configure SELinux permissions. Check the firewall rules. Troubleshoot other causes such as browser problems, server failures, or other possible errors.

How to start nginx in LinuxHow to start nginx in LinuxApr 14, 2025 pm 12:51 PM

Steps to start Nginx in Linux: Check whether Nginx is installed. Use systemctl start nginx to start the Nginx service. Use systemctl enable nginx to enable automatic startup of Nginx at system startup. Use systemctl status nginx to verify that the startup is successful. Visit http://localhost in a web browser to view the default welcome page.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.