Server deployment Nginx + Django + Vue

Welcome to click the link to jump to the Github Pages blog and enjoy a more comfortable typesetting interface.

This article records every step of my configuration and deployment of the server, mainly including the server configuration of the Django virtual environment, the use of uWSGI and Nginx, and the correction of errors. Take a Linux server as an example, so a certain knowledge base of Linux is required.

server preset

Rent a server

All major cloud platforms, such as Tencent Cloud, Alibaba Cloud, Huawei Cloud, etc., have student discounts. I chose Tencent Cloud here because the console interface is simple and elegant.

The relevant configuration is for reference only:

  • Mirror information: CentOS 7.6 64bit
  • Instance specifications: CPU 1 core, memory 2GB
  • Disk: system disk 40GB
  • Traffic package package: bandwidth 5Mbps, traffic package 1000GB/month (free)

SSH remote connection

Configure SSH remote connection to facilitate local operation of the server without having to log in to the cloud platform every time.

Click Login in the console to enter the server terminal. The first step is to initialize the password of the super user root and enter the superuser authority.

sudo passwd       # 初始化密码
su                # 切换到root超级用户

Modify the configuration file to allow password or key remote connection.

vim /etc/ssh/sshd_config      # 编辑ssh设置文件

In the opened file, modify:

RSAAuthentication yes                       # 开启rsa验证,需要添加
PubkeyAuthentication yes                    # 开启公钥登录,一般被注释掉了,去掉前面的#就好
AuthorizedKeysFile .ssh/authorized_keys     # 公钥保存位置,原来就有
PasswordAuthentication yes                  # 开启使用密码登录

Save and exit, and restart the SSH service.

service sshd restart        # 重启ssh服务

After setting, you can connect to the server locally with powershell or git bash.

ssh root@<IP address>       # IP address 为你服务器的公网IP地址

In addition, VScode's Remote - SSH remote connection plug-in is really fragrant.

Configure public key

After configuring the public key, connect to the server locally without entering the password every time.

First, generate the public key of the local computer.

ssh-keygen -t rsa           # 打开cmd或powershell输入

By default, just press Enter. After C:\Users\用户名\.sshsuccess , and will be id_rsagenerated under the folder id_rsa.pub, which is the key of the local user. Open the file and copy the contents. Then use the ssh command to log in to the remote server, create and enter the .ssh folder in the root directory of the root user, create an authorized_keys file, paste the key into it, and then restart the ssh service.

service sshd restart        # 重启ssh

Update system packages

The pre-configuration of the server is relatively old. Enter the following commands in sequence to upgrade software packages or dependencies.

yum update -y                               # 更新系统软件包
yum -y groupinstall "Development tools"     # 安装软件管理包
yum install openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel psmisc libffi-devel epel-release     # 安装可能使用的依赖

Configure Django

Install python3.8.4

cd /usr/local                   # 我一般喜欢把文件下载到该目录下
wget https://www.python.org/ftp/python/3.8.4/Python-3.8.4.tgz
tar -zxvf Python-3.8.4.tgz      # 解压python包

Enter the Python package path, and compile and install to the specified path /usr/local/python3

cd Python-3.8.4
./configure --prefix=/usr/local/python3
make && make install

After the installation is successful, establish a soft link and add environment variables. Because the server system comes with python, python2, and python3, I named it python3.8 to avoid conflicts. But my server only has pip3 and no pip, so I named the soft connection of pip3.8 pip.

ln -s /usr/local/python3/bin/python3.8 /usr/bin/python3.8
ln -s /usr/local/python3/bin/pip3.8 /usr/bin/pip

Check whether the installation is successful.

python3.8 -V
pip -V

Install the virtual environment

It is recommended to install the virtual environment virtualenv. When different python versions are required by different projects, there will be no conflicts.

pip install virtualenv
pip install virtualenvwrapper       # 管理虚拟环境

After the download is successful, create a directory to store the virtual environment.

mkdir ~/.virtualenvs                # 我一般存放在 /root/.virtualenvs,可自行修改

Find virtualenvwrapper.shthe file location, add the environment.

find / -name virtualenvwrapper.sh

Edit .bash_profilethe file and add these two sentences at the end, where sourcethe path after is the path found earlier.

export WORKON_HOME=$HOME/.virtualenvs
source  /usr/local/python3/bin/virtualenvwrapper.sh

After saving the modification, update the configuration information.

source ~/.bash_profile 

If an error is reported when saving, add the following content to /etc/profile, and then source.

export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3.8
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/python3/bin/virtualenv

Create a virtual environment

Specify the Python version used by -p, and automatically enter the virtual environment after the creation is successful.

mkvirtualenv -p python3.8 django        # django为虚拟环境名称

If you want to configure all plugins installed in the current virtual environment to the new virtual environment, you can execute:

pip freeze > requirements.txt           # 导出依赖
pip install -r requirements.txt         # 进入新虚拟环境后再执行

Other common commands for virtual environments

  • View all created virtual environments:workon
  • Use a virtual environment:workon 虚拟环境名称
  • Exit the current virtual environment:deactivate
  • Delete the virtual environment: rmvirtualenv 虚拟环境名称remember to exit and delete

Install Django and uWSGI in a virtual environment

uWSGI can be understood as a proxy server that continuously runs Django on the server, used for data transmission with the Django backend, etc., and needs to be used in subsequent configurations.

Enter the virtual environment created earlier and install.

pip install django==3.2         # 可指定版本
pip install uwsgi

uWSGI needs to be installed twice, once in the virtual environment and once out of the virtual environment for installation

Create a soft link to uWSGI.

ln -s /usr/local/python3/bin/uwsgi /usr/bin/uwsgi

Install Nginx

Nginx is an Http reverse proxy web server, and also provides IMAP/POP3/SMTP services, which takes up less memory and has strong concurrent capabilities. Here we only need to understand that Nginx can help us run our project on the designated port.

yum install nginx

After the installation is successful, the relevant file storage path is

  • After the installation is successful, the default website directory is/usr/share/nginx/html
  • The default configuration file is/etc/nginx/nginx.conf
  • The custom configuration file directory is/etc/nginx/conf.d/

Before starting, you also need to make sure that the relevant ports of the server are open. http corresponds to port 80, and https corresponds to port 443. Generally, for the server rented on the cloud platform, the corresponding port can be opened at the firewall in the console. My settings are for reference.

Next start Nginx

systemctl start nginx

After the startup is successful, the browser searches for the server IP address, and you can access the Nginx home page.

deployment project

upload project

The Django backend project file can be directly uploaded to the server. The front end written by the Vue framework needs to be packaged with npm run buildthe command , and then upload the generated dist directory.

The software FileZilla is recommended here , which is very convenient for local and server file transfer.

Configure uWSGI

Create a new file uwsgi.ini, which I am used to placing in the root directory of the Django project, to specify the project path, maximum number of processes, operating port, etc. My configuration parameters are available for reference.

[uwsgi]
socket = 127.0.0.1:8080
chdir = /root/Ops/django
wsgi-file = /root/Ops/django/django3/wsgi.py
master = true 
enable-threads = true
processes = 8
buffer-size = 65536
vacuum = true
daemonize = /root/Ops/django/uwsgi.log
virtualenv = /root/.virtualenvs/django
uwsgi_read_timeout = 600
threads = 4
chmod-socket = 664

Briefly introduce the configuration information of this file:

  • [uwsgi]: There must be this [uwsgi], otherwise an error will be reported
  • socket: This port is the running port of the backend Django, which can be customized, but it must be consistent with the configuration of Nginx later
  • chdir: django project path
  • wsgi-file: The wsgi.py file path of the django project
  • master: start the main process
  • processes: maximum number of processes
  • vacuum: Automatically delete unix socket files and pid files when the server exits
  • daemonize: output log, you can view it when there is an error
  • virtualenv: project virtual environment path

Switch the current path to the directory where the uwsgi.ini file is located, and start uWSGI.

uwsgi --ini uwsgi.ini

Use psthe command to view the process and check whether it is successful.

ps -aux | grep uwsgi

CSDN picture bed exploded

Configure Nginx

Here is an example of deploying a domain name first, and only the server IP will be given later.

First, /etc/nginx/nginx.confdelete server{...}the code in the section of the file. Of course, if you are afraid of making mistakes, you can also back up the original nginx.conf file first.

Next, modify the default file in /etc/nginx/conf.dthe folder default.conf(create a new one if it does not exist), the content of the file is as follows:

server {
    listen 80;
    listen 443 ssl;
    server_name  zewan.top www.zewan.top;

    location / {
        root /root/Ops/vue/dist;
        index index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    location /api {        
        include /etc/nginx/uwsgi_params;
        uwsgi_pass 127.0.0.1:8080;                                                               
    }

    ssl_certificate /etc/nginx/ssl/zewan.top.crt;
    ssl_certificate_key /etc/nginx/ssl/zewan.top.key;
    ssl_session_timeout  5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DH:!DHE;
    ssl_prefer_server_ciphers  on;

    error_page 497  https://$host$uri?$args;
}

A brief description of what the file content does:

  • listenFollowed by the port, which is the port for setting access, here both 80 and 443 are open
  • server_namedomain name for access
  • location /Then describe the storage address of the front-end dist project folder, which needs to be modified according to your own situation . Note that dist is the root directory of the front-end project
  • location /apiFinally, run the port for the backend project. Note uwsgi_passthat the configuration must be consistent with the previous uWSGI
  • ssl_certificate[_key]Store path for SSL certificate

important reminder

location /apiConnect with uWSGI, and finally run the backend on :443/api/. It is necessary to ensure that the routes of the backend are all api/*, that is, urls.pythe files must be added before all routes api/.

run project

Check whether the Nginx configuration is wrong, and restart the Nginx service after success.

nginx -t                # 测试
nginx -s reload         # 重新加载

Note that if you modify the backend Django content or other content, uWSGI and Nginx services must be restarted, otherwise it will not take effect!

ps -ef | grep uwsgi         # 查看uWSGI进程
killall -9 uwsgi            # 用kill方法把uwsgi进程杀死
uwsgi --ini uwsgi.ini       # 重启uwsgi
nginx -s reload             # nginx平滑重启

In addition, if your project files are stored in the root user directory, 500 or 403 Forbidden permission errors may appear when accessing the website. In this case, you need to modify the first/etc/nginx/nginx.conf line of the file to .user nginxuser root

Guess you like

Origin blog.csdn.net/weixin_45497461/article/details/119703036