It's time for everyone to see your blog written in Django (including deployment tutorial video)

Never give up 2021-10-25 23:47:11
time blog written django including

 It's time for everyone to see you use django Write a blog ( Including deployment tutorial video )

author :HelloGitHub- Dream chaser

The basic functions of blog have been developed , Although there are many places to improve , But we still hope to deploy the blog to the server earlier , Let others access through the Internet . As for the areas to be improved , You can iterate and improve a little bit after deployment . Now let's deploy the blog to the server !

↓↓↓ The video is here ↓↓↓

The whole process of real machine environment demonstration and deployment recorded by the author himself , If it doesn't work, you hit me !

B Station demonstration ( Alibaba cloud CentOS 7 System ) Viewing address :

Be careful : Every step of this paper is verified in real environment . Unless you know what you're doing , Otherwise, it is recommended to follow the instructions of the tutorial strictly , This will ensure that you can successfully complete the deployment .

Prepare for deployment

We will use the more popular Nginx + Gunicorn The way to django Deploy the developed blog to its own server , Let others access your blog through the domain name . as for Nginx、Gunicorn What is it? Put it aside , After reading this tutorial, you will know how to use them .

To deploy our blog , There are two conditions that need to be met :
  1. It is better to have a server that can be accessed through the Internet ( If not, you can build a virtual machine on your own computer , Through virtual ip visit ).
  2. It's better to have a domain name ( If not , Can only be used ip visit , And can't be opened HTTPS).

Configure server

The local environment used in this tutorial is Windows 10, The server environment is CentOS 7(64 position ). If your environment is different from mine ( such as Ubuntu) Causes some commands to fail to execute , Convert these commands to the command execution of your environment , The point is to understand the role of each step , So you can successfully deploy in any environment , Instead of mechanically copying and pasting commands .

Remote login to server

Servers are usually in the cloud , You need to use the remote login tool to log in before you can operate the server . I'm using Xshell,Windows Next Baidu Xshell Download and install , Software is free for schools and individual users .

How to log in to the server remotely is not covered here , I'm sure you can log in smoothly by referring to some online tutorials . If you use it like me Xshell Words , Here is a very detailed tutorial for reference : Teach you how to use it xshell Remote connection linux The server [2].

Create a super user

Successfully connected to the remote server , If it's a new server , Usually we use root User logged in . stay root The lower deployment code is not secure enough , It's better to build a new user ( If you have already made a mistake root Users can skip this step if they log in ). Some of the following commands will create a new user with super permissions ( hold yangxg Replace with the user name you want , I take my name Pinyin here yangxg):
# stay root Run this command under user to create a new user ,yangxg Is the user name # Because my name is Yang Xueguang , So my username is yangxg# Choose a user name you like , It doesn't have to be the same as mine [email protected]:~# adduser yangxg?# Set password for new users # Note that there will be no character display when inputting password , Don't think the keyboard is broken , Normal input is enough [email protected]:~# passwd yangxg?# Add the newly created user to the super permission group [email protected]:~# usermod -aG wheel yangxg?# Switch to the new user created [email protected]:~# su - yangxg?# Switch successful ,@ The symbol is already preceded by a new user name instead of root 了 [email protected]:$

New user created and switched successfully . If it's a new server , It's better to update the system first , Avoid the trouble of installing software later because the version is too old . Run the following two commands :
[email protected]:$ sudo yum [email protected]:$ sudo yum upgrade

to update SQLite3

For convenience , Our blog uses SQLite3 database ,django 2.2 requirement SQLite3 Database version in 3.8.3 above , and CentOS 7 The version of the system is lower than django 2.2 Minimum version required , So let's update it first SQLite3 Version of .

Be careful

It is possible that you use the server system distribution SQLite3 It is higher than 3.8.3, This step can be skipped . How to view SQLite3 The version of ? Please perform sqlite3 --version

First log in to sqlite The official download address of [3], View the latest release , By the end of this tutorial , Its latest version is 3.29.0, Find the source package of this version , Copy its download link , And then through wget Command download to server ( I usually put the source code in ~/src Under the table of contents .)
# establish src Directory and go to this directory [email protected]:$ mkdir -p ~/[email protected]:$ cd ~/src?# download sqlite3 Source code and decompression installation [email protected]:$ wget[email protected]:$ tar zxvf [email protected]:$ cd [email protected]:$ ./[email protected]:$ [email protected]:$ sudo make install

Tips: :

If wget The order does not exist , Use sudo yum install -y wget Can be installed .

thus SQLite3 Updated completely , Next install Python3.

install Python3 and Pipenv

CentOS 7 Self contained Python Issued as 2.7, So you need to install Python3, For compatibility , We installed Python 3.6.4.

Install possible dependencies first :
[email protected]:$ sudo yum install -y openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel

Then download Python 3.6.4 And decompress :
[email protected]:$ cd ~/[email protected]:$ wget[email protected]:$ tar -zxvf Python-3.6.4.tgz

Final build install :
[email protected]:$ cd [email protected]:$ ./configure LD_RUN_PATH=/usr/local/lib LDFLAGS="-L/usr/local/lib" CPPFLAGS="-I/usr/local/include"[email protected]:$ make LD_RUN_PATH=/usr/local/[email protected]:$ sudo make install

Pay attention to the installation here Python when ,Python Will depend on SQLite3 The library of , So in configure Through LD_RUN_PATH Specify the dependent search directory ( Because we updated it before SQLite3 Version of , Specify the dependent search directory to ensure the new SQLite3 Dependency Library ), The other two parameters have similar functions .

Then input python3.6 -V and pip3.6 -V Command test installation results , The output version number indicates that the installation is successful .

With pip, Can be installed Pipenv 了 :
[email protected]:$ sudo pip3.6 install pipenv

Tips: :

If the above command reports an error , Probably because pip3.6 Installed on the current user's bin Under the path (/usr/local/bin/), Use pip3.6 install pipenv --users Command also Pipenv Installed to the current user's bin Under the path .

Deployment code

Next, prepare the deployment code , Let our blog application run on the service , This is as like as two peas in the local development process. . But in order to deploy the application to the server , First of all, we need to do some configuration for the project , open, find ALLOWED_HOSTS, Change it to :
blogproject/settings.pyblogproject/ = ['', 'localhost ', '']

It specifies ALLOWED_HOSTS After the value of ,django Will only allow access to our app through the specified domain name , For example, it's only allowed to pass here,localhost as well as And any of its subdomains ( A dot before a domain name allows access to subdomains under that domain name ) visit ( namely HTTP In the message header Host The value of must be the domain name specified above , Usually when you enter a domain name in your browser to visit the website ,Host The value of will be set to the domain name of the website ), This can be avoided HTTP Host Head attack .

Django There will be some CSS、JavaScript Etc. static files , In order to be able to conveniently let Nginx Processing requests for these static files , We collect all the static files in the project into a unified directory , This directory is usually located in django The root directory of the project , And named it static. In order to accomplish these tasks , You need to make some necessary configuration in the configuration file of the project :
blogproject/ Other configuration ...?STATIC_URL = '/static/'# Add the following configuration STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATIC_ROOT That is, specify the collection path of static files , This is designated as BASE_DIR( Project root , stay Definition at the beginning of the document ) Under the static Folder .

Now the key is to send the code to the server , Here we use git. First installation git:
[email protected]:$ sudo yum install -y git

Upload the code to GitHub Wait for the code hosting platform , So we can easily pull the code to the server .Git and GitHub I believe you are familiar with the use of , I won't repeat the process here . If you don't know how to use it, you can do Baidu related courses by yourself . Do not upload the database file !

I usually like to put application code in ~/apps/ Under the table of contents , First, set up the file structure of the server , Used to store application code and other related documents :
# Create in user directory apps Directory and access [email protected]:$ mkdir -p ~/[email protected]:$ cd ~/apps?# Pull blog code [email protected]:$ git clone

Then go to the project root , Installation project dependency :
[email protected]:$ cd ~/apps/[email protected]:$ pipenv install --deploy --ignore-pipfile

Designated here --deploy Parameters ,Pipenv Will only be installed Pipfile in [packages] Dependency specified under . Because we are now deploying in an online environment , We don't need dependencies for development environments only .

--ignore-pipfile Will make Pipenv from Pipfile.lock Install project dependencies in file .Pipfile.lock Records the precise information on which the project depends , Reading dependency information from here can ensure that the dependency information is inadvertently modified or destroyed, which causes unexpected problems in the running environment due to the dependency package .

Pipenv Will automatically help us create a virtual environment , Then install the project dependency into the virtual environment .

Then create the database :
[email protected]:$ pipenv run python migrate

Start development server :
[email protected]:$ pipenv run python runserver

Here, when we start the development server, we specify the server running ip And port , This will allow access to the public network ip Of 8000 Port access to our blog .

visit ip:8000, You can see the success of the visit ( among ip For the public network of your server ip).

Use Gunicorn

Django Official documents emphasize the use of runserver Open development server for development testing only , Not recommended for production environments . So we use the popular Gunicorn To start a server that can be used in an online environment .

First go to the project root , install Gunicorn:
[email protected]:$ pipenv install gunicorn

Because we modified and installed it on the server gunicorn, In the code Pipfile Document and Pipfile.lock The file will be updated , So don't forget to synchronize the changes locally , You can learn by yourself , Here is a reference :
# Server submission code [email protected]:$ git add Pipfile [email protected]:$ git commit -m "add gunicorn dependency"[email protected]:$ git push?# Local pull code git pull

Back to the online server , In the project root directory , Start the service by executing the following command :
[email protected]:$ pipenv run gunicorn blogproject.wsgi -w 2 -k gthread -b

To explain the meaning of each parameter .

`-w 2 Said to start 2 individual worker Used to process requests ( One worker It can be understood as a process ), Will usually worker Number set to CPU Of the core number 2-4 times .

-k gthread Specify each worker How requests are processed , According to your practice , Designated as gthread High performance can be achieved by asynchronous mode of , So we use this model .

-b, Binding services to 8000 port , Operation through public network ip and 8000 Port access application .

visit ip:8000(ip For the public network of your server ip), App accessed successfully , But we saw that the pattern was completely out of order . Don't worry. , This is not bug! We used django Own development server , It will automatically help us with static style files , however Gunicorn It's not going to help us . Because processing static files is not Gunicorn What you are good at , It should be handed over to more professional service applications , such as Nginx.

start-up Nginx The server

Nginx (engine x) Is a high-performance HTTP And reverse proxy web The server , It has many functions , Here we mainly use it to process static files and reverse proxy requests of non static files to Gunicorn.

When we visit a blog post details page , The server receives the following two requests :
  • Show details of the article , This information is usually stored in a database , So we need to call the database to get the data .
  • picture 、css、js And so on .

For the previous request , The data of blog articles need help from django Get... From the database ,Nginx Can't handle , It will forward the request to Running on the Gunicorn In service django application , Give Way django To deal with . For the request of the latter static file , Just go to the folder where these static files are located to get ,Nginx They'll handle it for them , No more trouble django.

use django Getting static files is time consuming , but Nginx Can be handled efficiently , That's what we're going to use Nginx Why .

First installation Nginx:
[email protected]:$ sudo yum install epel-release [email protected]:$ sudo yum install nginx -y

Run the following command to start Nginx service :
[email protected]:$ sudo systemctl start nginx

Type in the browser ip( If no port is entered, the default value is 80 port ,Nginx Default in 80 Port listening requests ), notice Nginx Welcome interface description of Nginx It's working .

To configure Nginx

Nginx The configuration for is located at /etc/nginx/nginx.conf In file , You can open this file to see what's inside , Here are some key configurations :
user nobody nobody;...http { # Load modular configuration files from the /etc/nginx/conf.d directory. # See # for more information. include /etc/nginx/conf.d/*.conf;? server { listen 80 default_server; listen [::]:80 default_server; server_name _; root /usr/share/nginx/html;? # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf;? location / { } }}

The first is this user To configure , Is used to specify the Nginx Users and groups at process runtime ( First and second parameters respectively ), To prevent possible permission problems , We change to the current system user ( My user name is yangxg, Subordinate to the group yangxg, Remember to change to the users and groups running on your own server , Remember to save the contents of the file after modification ):
user yangxg yangxg;

And then in http Configuration next server modular ,server Module to configure a virtual service , Make this virtual service listen to the specified port and domain name . You can configure multiple server, This will start multiple virtual services , For listening to different ports , Or the same port , But different domain names , So you can deploy multiple on the same server web Applied .

This server We will explain the configuration of , Look again. server Under the include,include The configuration file in the specified path will be included , This facilitates modular management of configuration , For example, we can change web The configuration of the application is placed in /etc/nginx/conf.d/ Under the table of contents , such nginx Will put all the .conf The end of the file contains the contents of the nginx.conf In the configuration of , Without having to heap all the configurations to nginx.conf in , Make the configuration file very bloated .

Let's configure the blog app , It says , For modular management , We write the configuration to /etc/nginx/conf.d/ Under the table of contents . First on the server conf.d Create a new profile in the directory , I call it HelloDjango-blog-tutorial.conf. Write the following configuration :
server { charset utf-8; listen 80; server_name;? location /static { alias /home/yangxg/apps/HelloDjango-blog-tutorial/static; }? location / { proxy_set_header Host $host; proxy_pass; }}

First we configured a virtual service , The encoding method is utf-8, Monitor on 80 port .

The domain name of the service is, So requests from this domain will be processed by this service .

all URL matching /static All requests are made by Nginx Handle ,alias Indicates the directory where static files are stored , such Nginx You can find the requested file in this directory and return it to the client .

Other requests are forwarded to the local machine 8000 Application processing for port , We will start at this port Gunicorn Used for processing Nginx Forward the request .

restart nginx Make configuration effective :
[email protected]:$ sudo systemctl restart nginx

close DEBUG Pattern , Collecting static files

Under development environment ,django For debugging convenience , Will In the document DEBUG The options are configured to True, So if the program runs in error , Debugging information will be at a glance , This is convenient for development , But deployment online will bring huge security risks , So we put DEBUG Option set to False, Turn off debug mode , Local Medium DEBUG by :

Update the latest code of online server , Then run the command to collect the static files to the previously configured STATIC_ROOT Under the table of contents :
[email protected]:$ pipenv run python collectstatic

And then use Gunicorn Start the service .
[email protected]:$ pipenv run gunicorn blogproject.wsgi -w 2 -k gthread -b

Now? , Access the configured domain name Instead, you are Nginx Domain name configured in ), You can see the blog successfully deployed !

management Gunicorn process

Now? Gunicorn We started it by hand , Once we quit shell, The server is down , Blog unreachable . Even in the background Gunicorn, If one day the server crashes and restarts, you have to log in to the server again to start it , Very trouble . Use for this Supervisor To manage Gunicorn process , So when the server restarts or Gunicorn After an unexpected process crash ,Supervisor Will help us restart automatically Gunicorn.

According to the first Ctrl + C Stop what you just started Gunicorn Service process .

First installation Supervisor Pay attention to the use of System native pip2, Because as of the time of writing this tutorial Supervisor Not yet Python3, But this does not affect the use of .
[email protected]:$ pip install supervisor

For convenience , I usually set the following directory structure ( be located ~/etc Under the table of contents ) To manage Supervisor Relevant documents :
~/etc?├── supervisor│ ├── conf.d│ └── var│ ├── log└── supervisord.conf

among supervisord.conf yes Supervior Configuration file for , It will contain conf.d Configuration below .var The directory is used to store some frequently changed files , for example socket file ,pid file ,log Next, log files are stored .

First, establish the above directory structure :
[email protected]:$ mkdir -p ~/etc/supervisor/[email protected]:$ mkdir -p ~/etc/supervisor/var/log

Then enter ~/etc Generate under directory Supervisor Configuration file for :

modify supervisor.conf, Give Way Supervisor Some files generated by the process are generated in the directory we created above , Instead of its default designation .

First find [unix_http_server] Block , take file Change the setting to the following value :

That is to let socket File generated in ~/etc/supervisor/var/ Under the table of contents . Be careful supervisor No support will be made. ~ Expand to user home Catalog , So you have to specify the absolute path .

Similar modifications [supervisord] Under the plate logfile and pidfile Path to file , also user Change to system user , such supervisor The started process will run as a system user , Avoid possible permission issues :

also [supervisorctl] Under plate :

[include] Block , take /home/yangxg/etc/supervisor/conf.d/ All under the directory .ini The ending file content is included in the configuration , This facilitates modular management of configuration , And before Nginx Configuration files are handled in a similar way .
files = /home/yangxg/etc/supervisor/conf.d/*.ini

Then we go to conf.d New configuration of our blog app :
[program:hellodjango-blog-tutorial]command=pipenv run gunicorn blogproject.wsgi -w 2 -k gthread -b

Explain the meaning of each configuration :

[program:hellodjango-blog-tutorial] Indicates the process in which the application is running , be known as hellodjango-blog-tutorial.
  • command Commands to execute when starting a process .
  • directory Specifies the directory where the command is executed .
  • autostart along with Supervisor Start auto start process .
  • autorestart Restart when process exits unexpectedly .
  • user Users running the process , Prevent rights issues .
  • stdout_logfile,stderr_logfile Log output file .

start-up Supervisor
[email protected]:$ supervisord -c ~/etc/supervisord.conf

-c Appoint Supervisr Profile at startup .

Get into supervisorctl Process management console :
[email protected]:$ supervisorctl -c ~/etc/supervisord.conf

perform update Command to update the configuration file and start the application .

Browser input domain name , You can see that the service has started normally .

Use CDN To speed up the Bootstrap and jQuery Loading speed of

Our project uses Bootstrap and jQuery, We load these two files locally . If the performance of the server is poor , Loading takes a long time , The speed with which websites open becomes intolerable . We use CDN To speed up loading . say concretely , Replace base.html Load tags for several static files :
base.html?- <link rel="stylesheet" href="{% static 'blog/css/bootstrap.min.css' %}">- <script src="{% static 'blog/js/jquery-2.1.3.min.js' %}"></script>- <script src="{% static 'blog/js/bootstrap.min.js' %}"></script>+ <link href="" rel="stylesheet">+ <script src=""></script>+ <script src=""></script>

After local code modification , Sync code to online server , Perform the following command to restart hellodjango-blog-tutorial Application process :
[email protected]:$ supervisorctl -c ~/etc/supervisord.conf restart hellodjango-blog-tutorial

In this way, the speed of website visit will be greatly improved !


There are many and complicated deployment steps , Because every environment is different , So deployment is the most error prone step , Be sure to understand the function of each step , In this way, in case of problems , To solve the problem , If you only know the copy and paste command , I don't know what I'm doing , So if something goes wrong, there's nothing we can do .

Deployment process automation

We ran a dozen commands throughout the deployment , Entered manually N Characters . It will be very troublesome to connect to the server remotely to execute these commands every time the code is updated . In the next tutorial, we will introduce how to use Fabric Automate the entire deployment process . After writing the deployment script , Just one command to execute , It's very easy to automate the entire deployment .


[1]HelloGitHub-Team Warehouse :

[2] Teach you how to use it xshell Remote connection linux The server :

[3]sqlite The official download address of :

『 Explain the open source project series 』—— Let people who are interested in open source projects no longer fear 、 Let the developers of open source projects no longer be alone . Follow our article , You'll find programming fun 、 Using and discovering open source projects is so easy . Welcome to contact us 、 Join us , Let more people fall in love with open source 、 Contribute to open source ~

本文为[Never give up]所创,转载请带上原文链接,感谢

  1. 你需要知道的 20 个 Python 技巧
  2. 如何在 Python 中搜索和替换文件中的文本?
  3. 只需 15 行代码即可进行人脸检测!(使用Python 和 OpenCV)
  4. Python中选择结构问题求解
  5. La détection faciale ne nécessite que 15 lignes de code! (en utilisant Python et OpenCV)
  6. Comment rechercher et remplacer du texte dans un fichier en python?
  7. 20 conseils Python que vous devez connaître
  8. python计算机视觉项目供Java后端调用
  9. python計算機視覺項目供Java後端調用
  10. Python Computer Vision Project for Java Backend Calls
  11. Résoudre le problème de la structure de sélection en python
  12. 使用Python,OpenCV的Meanshift 和 Camshift 算法來查找和跟踪視頻中的對象
  13. Trouver et suivre des objets dans la vidéo en utilisant Python, les algorithmes meanshift et camshift d'OpenCV
  14. Visualisation python - solutions de dessin 3D pyecharts, matplotlib, openpyxl
  15. Automatically generate API documents from Python source code comments
  16. 下载pandas出错了,怎么解决啊
  17. Une erreur s'est produite lors du téléchargement de pandas.
  18. Python Type Hints 从入门到实践
  19. Python Type Hints 從入門到實踐
  20. Type Python hints from starting to Practice
  21. django channels channel_layer.group_send 造成内存溢出
  22. Python布置了个感觉不大理解的题..
  23. Python a posé une question qui ne semblait pas très compréhensible.
  24. Python中yield返回生成器的详细方法
  25. Python函数中apply、map、applymap的区别
  26. Python字符串前加f、r、b、u的不同用法
  27. 5分钟教会你用Python采集CSDN的热榜
  28. 5分鐘教會你用Python采集CSDN的熱榜
  29. 5 minutes pour vous apprendre à utiliser Python pour collecter des listes chaudes de csdn
  30. Quick start of automation -- python (1) - [variables] - half an hour a day
  31. Python爬虫:给我一个链接,快手视频随便下载
  32. Python爬蟲:給我一個鏈接,快手視頻隨便下載
  33. 经验丰富程序员才知道的15种高级Python小技巧
  34. 經驗豐富程序員才知道的15種高級Python小技巧
  35. 15 conseils Python avancés que les programmeurs expérimentés connaissent
  36. Python crawler: Donnez - moi un lien pour télécharger des vidéos rapides
  37. Python爬虫:给我一个链接,快手视频随便下载
  38. [algorithm learning] sword finger offer 64. Find 1 + 2 +... + n (Java / C / C + + / Python / go / trust)
  39. 怎么系统的学习python,有没有一些比较完整的资料,基础知识+框架+项目实战此类pdf
  40. Python crawler: Donnez - moi un lien pour télécharger des vidéos rapides
  41. Python project management and construction, these four tools are enough!
  42. IDE的使用,pycharm引入Python库
  43. In the 120 series columns, you can learn the python beautiful oup4 module, 7000 word blog + climb the ninth workshop network
  44. Django运行xadmin 报错解析 ImportError: cannot import name 'DEFAULT_FORMATS' from 'import_export.admin'
  45. Python程序大学课程写程序
  46. Programme Python Programme d'études collégiales
  47. Python程序大學課程寫程序
  48. Django runxadmin Error resolution importerror: cannot Import name 'default Formats' from 'import _ Export.admin»
  49. Python 函数式编程,看这一篇足够了!
  50. 太棒了!11个好用到起飞的「Python字典」知识点!
  51. 一道Python题目,求解答!
  52. 一道Python題目,求解答!
  53. Un problème Python, s'il vous plaît!
  54. C'est génial! 11 points de connaissance du dictionnaire Python pour le décollage!
  55. Python Functional Programming, This is enough!
  56. 在python中beta分布的问题?
  57. 一个python习题,没有什么头绪,是关于进制的转换和绘制的,想了几天了,不仅仅是2,8,16这种常见的进制转换
  58. Un exercice Python, qui n'a pas beaucoup d'idées, est sur la conversion et le rendu décimaux et a pensé pendant quelques jours, pas seulement 2, 8, 16 cette conversion décimale commune
  59. Un problème avec la distribution bêta en python?
  60. python实现简单的读取excel 内容,报错