search
HomeOperation and MaintenanceNginxHow to configure a Python web project using Nginx and uWSGI

For python-based web projects, common deployment methods are:

  • fcgi: Use spawn-fcgi or the tools that come with the framework to generate listening processes for each project, and then use them with http Service interaction.

  • wsgi: Use the mod_wsgi module of the http service to run each project.

But there is also uwsgi, which neither uses the wsgi protocol nor the fcgi protocol. Instead, it creates its own uwsgi protocol. According to the author, this protocol is about 10 times as powerful as the fcgi protocol. so fast. The main features of uwsgi are as follows:

  • Ultra-fast performance.

  • Low memory usage (measured to be about half of apache2’s mod_wsgi).

  • Multi-app management.

  • Detailed log function (can be used to analyze app performance and bottlenecks).

  • Highly customizable (memory size limit, service restart after a certain number of times, etc.).

Environment ubuntu 12.04 ip:10.1.6.79

Install nginx

apt-get install nginx-full nginx-common

nginx configuration/etc/nginx/sites- enabled/example

server {
    listen     80;
    server_name   10.1.6.79;
    access_log   /var/log/nginx/example_access.log;
    error_log    /var/log/nginx/example_error.log;
    root      /var/www/example;
    location / {
      uwsgi_pass   127.0.0.1:9001;
      include     uwsgi_params;
      uwsgi_param   uwsgi_scheme $scheme;
      uwsgi_param   server_software  nginx/$nginx_version;
    }
}

Install uwsgi

apt-get install uwsgi uwsgi-plugin-python

If you want to install all uwsgi plug-ins, you can install the uwsgi-plugin-all package

uwsgi configuration/etc/uwsgi/apps-enabled/default.xml

<uwsgi>
  <plugin>python</plugin>
  <socket>127.0.0.1:9001</socket>
  <pythonpath>/var/www/example/app/</pythonpath>
  <app mountpoint="/">
    <script>wsgi_configuration_module</script>
  </app>
  <master/>
  <processes>4</processes>
  <reload-mercy>8</reload-mercy>
  <cpu-affinity>1</cpu-affinity>
  <max-requests>2000</max-requests>
  <limit-as>512</limit-as>
  <reload-on-as>256</reload-on-as>
  <reload-on-rss>192</reload-on-rss>
  <no-orphans/>
  <vacuum/>
</uwsgi>

The parameters in the uwsgi configuration file can also be specified through uwsgi on the command line. In addition to the xml format, the configuration file can also be written in ini format. After the software package is installed, there will be some examples of xml and ini format configuration files in the /usr/share/doc/uwsgi/examples/conffile directory.

wsgi_configuration_module.py script content

#!/usr/bin/python
import os
import sys
sys.path.append(&#39;/var/www/example/app&#39;)
os.environ[&#39;python_egg_cache&#39;] = &#39;/var/www/example/.python-egg&#39;
def application(environ, start_response):
  status = &#39;200 ok&#39;
  output = &#39;hello world!&#39;
  response_headers = [(&#39;content-type&#39;, &#39;text/plain&#39;),
          (&#39;content-length&#39;, str(len(output)))]
  start_response(status, response_headers)
  return [output]

Start uwsgi

uwsgi -x /etc/uwsgi/apps-enabled/default.xml --daemonize /var/log/uwsgi/app/default.log

uwsgi parameters:
-m Start the master process
-p 4 Start 4 processes
-s The port or socket address used
-d Use daemon mode to run. Note that after using -d, you need to add the log file address, such as -d /var/log/uwsgi .log
-r 10000 After opening 10,000 processes, automatically respawn
-t 30 Set a timeout of 30s. After the timeout, the link will be automatically abandoned
–limit-as 32 The total memory amount of the process Controlled at 32m
-x Use configuration file mode

Concurrent 4 threads

uwsgi -s :9090 -w myapp -p 4

Main control thread 4 threads

uwsgi -s :9090 -w myapp -m -p 4

Execution exceeds The client will give up directly after 30 seconds

uwsgi -s :9090 -w myapp -m -p 4 -t 30

Limit the memory space to 128m

uwsgi -s :9090 -w myapp -m -p 4 -t 30 --limit-as 128

Serve more than 10,000 reqs and automatically respawn

uwsgi -s :9090 -w myapp -m -p 4 -t 30 --limit-as 128 -r 10000

run in the background, etc.

uwsgi -s :9090 -w myapp -m -p 4 -t 30 --limit-as 128 -r 10000 -d uwsgi.log

In addition to starting directly with the uwsgi command, you can also start it with the script under init.d. However, you need to modify the path of the default configuration file in /etc/default/u wsgi first, and then use / etc/init.d/uwsgi startStart

#inherited_config=/usr/share/uwsgi/conf/default.ini
inherited_config=/etc/uwsgi/apps-enabled/default.xml

Start nginx

/etc/init.d/nginx start

The effect is as follows:

How to configure a Python web project using Nginx and uWSGI

Test whether uwsgi is available
Test script test.py

#!/usr/bin/python
def application(env,start_response):
  start_response(&#39;200 ok&#39;,[(&#39;content_type&#39;,&#39;text/html&#39;)])
  return "congraduation!!! uwsgi testing ok!!!
#启动web server
uwsgi --http :9090 --wsgi-file test.py

Browser input ip: port: 192.168.1.99:9090
You can see "congraduation !!!uwsgi testing ok!!!”

The above is the detailed content of How to configure a Python web project using Nginx and uWSGI. 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 vs. Apache: Examining the Pros and ConsNGINX vs. Apache: Examining the Pros and ConsApr 27, 2025 am 12:05 AM

NGINX is suitable for handling high concurrent and static content, while Apache is suitable for complex configurations and dynamic content. 1. NGINX efficiently handles concurrent connections, suitable for high-traffic scenarios, but requires additional configuration when processing dynamic content. 2. Apache provides rich modules and flexible configurations, which are suitable for complex needs, but have poor high concurrency performance.

NGINX and Apache: Understanding the Key DifferencesNGINX and Apache: Understanding the Key DifferencesApr 26, 2025 am 12:01 AM

NGINX and Apache each have their own advantages and disadvantages, and the choice should be based on specific needs. 1.NGINX is suitable for high concurrency scenarios because of its asynchronous non-blocking architecture. 2. Apache is suitable for low-concurrency scenarios that require complex configurations, because of its modular design.

NGINX Unit: Key Features and CapabilitiesNGINX Unit: Key Features and CapabilitiesApr 25, 2025 am 12:17 AM

NGINXUnit is an open source application server that supports multiple programming languages ​​and provides functions such as dynamic configuration, zero downtime updates and built-in load balancing. 1. Dynamic configuration: You can modify the configuration without restarting. 2. Multilingual support: compatible with Python, Go, Java, PHP, etc. 3. Zero downtime update: Supports application updates that do not interrupt services. 4. Built-in load balancing: Requests can be distributed to multiple application instances.

NGINX Unit vs. Other Application ServersNGINX Unit vs. Other Application ServersApr 24, 2025 am 12:14 AM

NGINXUnit is better than ApacheTomcat, Gunicorn and Node.js built-in HTTP servers, suitable for multilingual projects and dynamic configuration requirements. 1) Supports multiple programming languages, 2) Provides dynamic configuration reloading, 3) Built-in load balancing function, suitable for projects that require high scalability and reliability.

NGINX Unit: The Architecture and How It WorksNGINX Unit: The Architecture and How It WorksApr 23, 2025 am 12:18 AM

NGINXUnit improves application performance and manageability with its modular architecture and dynamic reconfiguration capabilities. 1) Modular design includes master processes, routers and application processes, supporting efficient management and expansion. 2) Dynamic reconfiguration allows seamless update of configuration at runtime, suitable for CI/CD environments. 3) Multilingual support is implemented through dynamic loading of language runtime, improving development flexibility. 4) High performance is achieved through event-driven models and asynchronous I/O, and remains efficient even under high concurrency. 5) Security is improved by isolating application processes and reducing the mutual influence between applications.

Using NGINX Unit: Deploying and Managing ApplicationsUsing NGINX Unit: Deploying and Managing ApplicationsApr 22, 2025 am 12:06 AM

NGINXUnit can be used to deploy and manage applications in multiple languages. 1) Install NGINXUnit. 2) Configure it to run different types of applications such as Python and PHP. 3) Use its dynamic configuration function for application management. Through these steps, you can efficiently deploy and manage applications and improve project efficiency.

NGINX vs. Apache: A Comparative Analysis of Web ServersNGINX vs. Apache: A Comparative Analysis of Web ServersApr 21, 2025 am 12:08 AM

NGINX is more suitable for handling high concurrent connections, while Apache is more suitable for scenarios where complex configurations and module extensions are required. 1.NGINX is known for its high performance and low resource consumption, and is suitable for high concurrency. 2.Apache is known for its stability and rich module extensions, which are suitable for complex configuration needs.

NGINX Unit's Advantages: Flexibility and PerformanceNGINX Unit's Advantages: Flexibility and PerformanceApr 20, 2025 am 12:07 AM

NGINXUnit improves application flexibility and performance with its dynamic configuration and high-performance architecture. 1. Dynamic configuration allows the application configuration to be adjusted without restarting the server. 2. High performance is reflected in event-driven and non-blocking architectures and multi-process models, and can efficiently handle concurrent connections and utilize multi-core CPUs.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function