程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django deployment

編輯:Python

Django Deploy :Python + ubuntu + Nginx + uWSGI + Django

author:Once Day date:2022 year 2 month 13 Japan

The purpose of this document is to summarize the relevant contents , Scattered knowledge is difficult to remember and learn .

This document is based on windows platform .

View a full range of documents :Django Basic knowledge of _CSDN Blog .

1. Preface

Django The main deployment mode of is WSGI, It is Web The server and Web Applied Python standard , It is also the so-called synchronization service and default service .Django Support :

  • Gunicorn
  • uWSGI
  • Apache
  • Nginx

Here are two of them Nginx+uWSGI.

use WSGI The key to deployment is a process called application Callable object of , The application server uses it to interact with your code , Is the interface and entry for all requests . We use startproject When the command creates a project, it automatically creates /wsgi.py file , That's included application object , It can be used directly .Django Development server and production environment WSGI Use it for deployment .

WSGI The server gets... From its configuration file application The path to the object .Django Development server for ( runserver ), From configuration item WSGI_APPLICATION In order to get . The default value is .wsgi.application, Point to /wsgi.py Medium application .

When WSGI The server (uWSGI、Gunicorn etc. ) When loading the application ,Django You need to import the configuration module .

Django utilize DJANGO_SETTINGS_MODULE Environment variables to determine which settings.py modular , Its value is a dot path string . The development environment and the production environment can be configured differently settings.py.

If this variable is not set , wsgi.py It is set to... By default your_site.settings, your_site Project name .

Be careful : Because the environment variables are process level , So if you run multiple in the same process Django The site will go wrong . To avoid this problem , Can be used for each site mod_wsgi Of daemon Pattern . Or in wsgi.py Mandatory settings in os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" , Rewrite the value from the environment variable .

2. install Django

stay Ubuntu The system comes with python, It should be noted that points python2 and python3 Two kinds of , We're going to use python3, This is something to pay attention to !

Just use the command :

pip3 install django

But in fact, there may be various problems and failures , So you can refer to the documentation : First time to know django. There are more details !

3. install Nginx

Ubuntu In the default source Nginx The version is older , You need to add a Nginx Source , Re pass apt-get install Nginx.

sudo add-apt-repository ppa:nginx/stable
apt-get update
apt-get install nginx

Nginx The installation of is relatively smooth !

use ifconfig Instruction query native IP Address and browser access , notice “Welcome to nginx” The words... , The installation is successful !

without , it is to be noted that nginx The service is not started , Available at this time

service --status-all

Inquire about , notice nginx The front is + Number , That means the service is started !

......
[ + ] network-manager
[ + ] networking
[ + ] nginx
......

Use the following command :

sudo service nginx start
sudo service nginx stop
sudo service nginx restart

Can be opened 、 close 、 restart nginx service !

4. install uWSGI

uWSGI Is to implement the WSGI Agreed WSGI The server . It's a fast one 、 Self driven 、 Application container server friendly to developers and system administrators , Completely by C To write .

uWSGI Official website : Official website .

As the installation process needs to be carried out C Language compilation and python Library function reference , Therefore, additional software package support is required , Please make sure to take the following steps , Please refer to the official installation procedures for details :Installing uWSGI — uWSGI 2.0 documentation (uwsgi-docs.readthedocs.io)

1. install development headers

apt-get install build-essential python3

2. install python/wsgi support

apt-get install python3.8-dev

Notice the python The version must be consistent with the python Version up , Otherwise follow-up uWSGI Error will be reported in compilation !.

3. Determine if make You can use (gcc,g++ You can use )

python uwsgiconfig.py --build

4. Installation and compilation uWSGI

# Install the latest stable release:
pip install uwsgi
# ... or if you want to install the latest LTS (long term support) release,
pip install https://projects.unbit.it/downloads/uwsgi-lts.tar.gz

There are two options , Stable version and latest version , Recommend the latest version ! That's the second one !

It is worth noting that ,uWSGI It is used after compilation , It means and python Version is bound , Even with the platform !

At the end of the above steps , Run... Can try uwsgi, See if the installation is successful !

5. To configure uwsgi

The first Django Upload the project to the server !

stay Django The root directory of the project , There is a manage.py Under the directory of , Create a new one uwsgi.ini file . The file name can be arbitrary , But the suffix must be ini.

If you don't know Django project , It is suggested to study first Django Project creation for !

stay uwsgi.ini Write the following code to the file :

[uwsgi]
chdir = /..../project
# Project root
module = project.wsgi:application
# Appoint wsgi Under the module of application object
socket = 127.0.0.1:8000
# For this machine 8000 Ports provide services
master = true
# The main process
# above 4 The first is the core configuration item
#vhost = true // Multi station mode
#no-site = true // In multi station mode, no entry module or file is set
#workers = 2 // Number of child processes
#reload-mercy = 10
#vacuum = true // sign out 、 Clean up files on restart
#max-requests = 1000
#limit-as = 512
#buffer-size = 30000
#pidfile = /var/run/uwsgi9090.pid
#pid file , Used for script startup 、 Stop the process
daemonize = Project root /run.log
# Log files
disable-logging = true
# Do not record normal information , Only error messages are recorded

Detailed instructions :

  • In the configuration item, the ‘#’ The beginning is the annotated items , It doesn't work ;
  • Start with a double slash , Notation ;
  • chdir Is your project root directory . My project here is called for_test;
  • moudule It's your entrance wsgi modular , take for_test Replace with your project name ;
  • socket Is the communication port setting , Just like me ;
  • master=True Indicates running in main process mode ;
  • demonize It's your log file , Will automatically create
  • disable-logging = true Indicates that normal information is not recorded , Only error messages are recorded . Otherwise, your log may be full soon .
  • env: Appoint DJANGO_SETTINGS_MODULE Value
  • home: Optional project virtual environment path

You can also use command parameters , But it seems complicated and can't be modified :

uwsgi --chdir=/path/to/your/project \
--module=mysite.wsgi:application \
--env DJANGO_SETTINGS_MODULE=mysite.settings \
--master --pidfile=/tmp/project-master.pid \
--socket=127.0.0.1:49152 \ # can also be a file
--processes=5 \ # number of worker processes
--uid=1000 --gid=2000 \ # if root, uwsgi can drop privileges
--harakiri=20 \ # respawn processes taking more than 20 seconds
--max-requests=5000 \ # respawn processes after serving 5000 requests
--vacuum \ # clear environment on exit
--home=/path/to/virtual/env \ # optional path to a virtual environment
--daemonize=/var/log/uwsgi/yourproject.log # background the process

6. To configure Nginx

Backup /etc/nginx/sites-available In the folder default file , Then edit it ( Different Nginx The version may be configured differently ):

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##
# Default server configuration
#
server {
listen 80;
listen [::]:80;
# SSL configuration
#
# listen 443 ssl default_server;
# listen [::]:443 ssl default_server;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
# root /var/www/html;
# Add index.php to the list if you are using PHP
# index index.html index.htm index.nginx-debian.html;
server_name 192.168.1.121;
# Fill in the service name 2 The address or domain name of the external service
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
# try_files $uri $uri/ =404;
include uwsgi_params;
uwsgi_pass 127.0.0.1:8000;
}
location /static {
alias / Project root /static;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# include snippets/fastcgi-php.conf;
#
# # With php7.0-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# # With php7.0-fpm:
# fastcgi_pass unix:/run/php/php7.0-fpm.sock;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
# listen 80;
# listen [::]:80;
#
# server_name example.com;
#
# root /var/www/example.com;
# index index.html;
#
# location / {
# try_files $uri $uri/ =404;
# }
#}

The key is this part :

server {
listen 80;
listen [::]:80;
server_name 192.168.1.121;
location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:8000;
}
location /static {
alias Project root /static;
}
}

Please put server_name Change to your actual IP.include uwsgi_params It has to be the same .uwsgi_pass And you uWSGI The configuration of the socket To be the same .location /static Of alias Change to your actual situation , Allow static files to be deployed .

The modification is complete , Save and exit , And then restart nginx service :

sudo service nginx restart

7. Start the service

Now we can try to start the service ! Go to the root of the project , There is a uwsgi.ini Where the papers are , function :

sudo uwsgi uwsgi.ini

System prompt :

[uWSGI] getting INI configuration from uwsgi.ini

At this point, your website page will show that you are not allowed !

Enter the corresponding directory , edit settings.py file :

DEBUG = False
ALLOWED_HOSTS = ['192.168.1.121']

At the same time DEBUG Set to False. Such as :

Invalid HTTP_HOST header: '192.168.1.121'. You may need to add '192.168.1.121' to ALLOWED_HOSTS.

Enter the corresponding directory of the project , edit settings.py file :

DEBUG = False
ALLOWED_HOSTS = ['192.168.1.121','www.onceday.work']

You can fill in the domain name here , Also can be filled IP Address !

At the same time DEBUG Set to False.

stay ubuntu in , Run the following command :

sudo killall -9 uwsgi

This will delete the previous uWSGI process . Then wait a few seconds ,

sudo uwsgi uwsgi.ini

This is because there is a delay in port release .

8. matters needing attention

Static files are nginx Directly distributed , In the configuration, it is ,

location /static {
alias Project root /static;
}

explain url The address is /static/xxxx/xxx The match is here , And then change to Project root /static/xxxx/xxx, In fact, this already means that all static files need to be collected together !

But if you don't collect it , You need to fill in... When quoting static files Project root to file The address of , namely xxxx/xxx part , Because you are nginx At most, it refers to a fixed address , For example, the static folder under the project root directory !

Recommended references :
  • Use WSGI Deployment _w3cschool

  • Deploy static articles _w3cschool

  • django Deploy Django - Liu Jiang's django course (liujiangblog.com)

  • Installing uWSGI — uWSGI 2.0 documentation (uwsgi-docs.readthedocs.io)

notes : The content of this article is collected and summarized on the Internet , For learning only !

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved