Python + Django4 to build a personal blog (20): Alibaba Cloud deployment blog project

In this article we will complete the last part of our core function of building a personal blog: deployment and launch.

In the next part, we will update some other blog functions from time to time, such as article columns, message notifications, user extensions and other small functional modules.


Table of contents

Prepare server

Install Xshell and Xftp

Server installation software

Install Mysql

Modify Django project configuration file

Transfer Django project to server

Nginx configuration

Prepare backend users and enable Gunicorn

Test and run


In this article, we will use Nginx and Gunicorn to implement website projects and implement online deployment of Django projects on Alibaba Cloud.

During development, we used Django's own development server, but its performance was too poor to be used in an online environment. Therefore, when deploying online, we not only need to install Django, but also Nginx and Gunicorn. The workflow of these three brothers is as follows:

  • The client sends an http request, and Nginx serves as a direct external server interface to analyze the http request.
  • If it is a static resource request, it will be handled by Nginx itself (extremely efficient)
  • If it is a dynamic resource request, forward it to Gunicorn
  • After Gunicorn preprocesses the request, forward it to Django, and finally completes the return of the resource.

The steps to deploy a Django project are roughly as follows:

  • Prepare the server (open port 80)
  • Prepare tools for remote connection to the server and file transfer (Xshell and Xftp)
  • Install Python, Nginx, Mysql
  • Create database
  • Modify Django project configuration file
  • Transfer Django project to server
  • Install the relevant Python packages contained in the project Requirements.txt
  • Collect static resources
  • Configure Nginx related proxy parameters
  • Install and enable Gunicorn
  • test run

Prepare server

This article uses Alibaba Cloud. Alibaba Cloud servers can be tried for one month. We use the trial server as an example to implement project deployment.

In the service activation interface, you can fill in the other information as you like. We use Ubuntu 22.04 64-bit version of the operating system.

When activating it, we choose only the operating system and no other applications are pre-installed.

After activation, enter the management instance interface and you can see our most critical field content, public IP:39.107.240.223

Then reset our instance password (otherwise the secret key will be used by default when logging in to the server)

Then check the inbound ports in our security group. At least ports 80 and 22 need to be open.

Install Xshell and Xftp

Xshell and Xftp are remote tools developed by NetSarang.

  • Xshell can remotely connect and control the server
  • Xftp can remotely transfer files to the server

The download address is as follows. For personal use, just use the free version.

Free for home/school - NetSarang Website https://www.xshell.com/zh/free-for-home-school/

After installing the software, we first open Xshell, create a new session, and enter the public network address of Alibaba Cloud on the host.

Select User Authentication, enter your login username and password and click the Connect button to complete the login.

The installation and login methods of Xftp and Xshell are almost the same, so there will be no special introduction here.

Server installation software

Before installing the software, we first upgrade the version of the system library to prevent problems caused by out-of-date system versions.

~$ sudo apt-get update
~$ sudo apt-get upgrade

Install the necessary software: Nginx, Python, PIP, and PIP installs the Python virtual environment virtualenvlibrary.

~$ sudo apt-get install nginx
~$ sudo apt-get install python3
~$ sudo apt-get install python3-pip
~$ sudo pip3 install virtualenv

Install Mysql

sudo apt install mysql-server

Check running status

sudo systemctl status mysql

After the installation is complete, use the command to log in directly as the root user.

sudo mysql

(On MySQL 8.0, the root user is authorized through the auth_socket plug-in by default and cannot log in with a password. Password login can only be enabled after changing the password.)

Then enter the following two commands in the mysql command interface to change the root user's password to your latest password:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'newpassword';

mysql> FLUSH PRIVILEGES;

Exit mysql:

mysql> exit

Then check whether logging in using the root password is successful:

mysql -u root -p

The following interface represents successful login.

Conveniently, we created the database together (as long as the name is the same as the one we created locally):

mysql> CREATE DATABASE IF NOT EXISTS django_blog DEFAULT CHARSET utf8;

Modify Django project configuration file

If we deploy the project online, we need to modify the configuration file django4blog/settings.py.

DEBUG = False

ALLOWED_HOSTS = ['*']

# 静态文件收集目录
STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static')

Mainly involves 3 points:

  • Turn off debugging mode when deploying to avoid security issues (Django will no longer process static resources at this time).
  • ALLOWED_HOSTS specifies the server name or IP that is allowed to access, and the asterisk indicates that all requests are allowed. Please change it to your domain name or IP during actual deployment, such as ALLOWED_HOSTS = [ '127.0.0.1'].
  • There are many static files in the project. When deploying, you need to find a place to collect them uniformly, which is the address specified by STATIC_ROOT. After specifying this address, Django can use the command to collect all (including the Admin page that comes with Django) during deployment. Related) static resources (css, js, etc.) are all collected into designated folders, which makes it easier for us to load them uniformly during deployment.

Then we need to modify the configuration to solve the cross-domain problem of online deployment:

First install the package with PIP django-cors-headers:

pip install django-cors-headers

Then modify the configuration filedjango4blog/settings.py

INSTALLED_APPS = [
    ......
    'corsheaders',  #解决浏览器跨域问题
    ......
]

MIDDLEWARE = [
    ......
    'corsheaders.middleware.CorsMiddleware',  #解决浏览器跨域问题
    'django.middleware.common.CommonMiddleware', #解决浏览器跨域问题
    ......
]

CORS_ORIGIN_ALLOW_ALL = True #解决浏览器跨域问题
CORS_ALLOW_CREDENTIALS = True #解决浏览器跨域问题

SECURE_CROSS_ORIGIN_OPENER_POLICY = 'None'  #Django4 特定解决浏览器跨域问题

In addition, if our server database password is inconsistent with the local database password, we can modify the parameters of the configuration file in advance:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',    # 数据库引擎
        'NAME': 'django_blog', # 数据库名称
        'HOST': '127.0.0.1', # 数据库地址,本机 ip 地址 127.0.0.1
        'PORT': 3306, # 端口
        'USER': 'root',  # 数据库用户名
        'PASSWORD': 'newpassword', # 数据库密码 修改为服务器数据库密码
    }
}

Finally, we make a list of the libraries we need to use in our local project so that they can be installed uniformly on the server.

Enter the command in the local virtual environment:pip freeze > requirements.txt

(env) E:\django_project\django4blog>pip freeze > requirements.txt

Get the library manifest file requirements.txt.

Transfer Django project to server

After revising the local project parameters, we log in to Xftp and directly copy the local project folder django_projectto the server

Return to the server operation interface of Xshell and enter our project folderdjango_project

cd django_project

Then generate a virtual environment on the server:

virtualenv --python=python3.10 myenv

Enter the virtual environment:

source env/bin/activate

Go to django4blogthe project folder:

cd django4blog

Enter the following command to install the necessary Python libraries for the project.

(env) ../django4blog# pip3 install -r requirements.txt

If pip3 install -r requirements.txtthe following error occurs during the command.

This is because the version of the local tzdata library is too high. Alibaba's mirror version currently only supports 2022.4. At this time, we can directly modify the tzdata version in requirements.txt to 2022.4.

The Ubuntu file modification command is as follows:

vi requirements.txt,open a file

Press the Insert or i key to start modifying the file and change the tzdata version to 2022.4

After the modification is completed, press the Esc key first, then enter the command :wqto save and exit the file.

Re-execute the command

pip3 install -r requirements.txt

Successful installation

Then enter the following commands to complete static resource collection and data migration.

(env) ../django4blog# python3 manage.py collectstatic
(env) ../django4blog# python3 manage.py migrate

At this point, our deployment work for the development and coding part has ended.

Nginx configuration

The next step is to enable Nginx and configure related proxies.

First, we delete the default configuration and connection files of Nginx default.

Enter separately /etc/nginx/sites-availableand /etc/nginx/sites-enabledenter the commands in the two folders:

sudo rm -r defaultDelete defaultfiles.

Then we enter /etc/nginx/sites-availableand create a new configuration file of our own:django4blog

(myenv) root.../etc/nginx/sites-available# cd /etc/nginx/sites-available
(myenv) root.../etc/nginx/sites-available# vi django4blog

Enter the following configuration content:

server {
  charset utf-8;
  listen 80;
  server_name 39.107.240.223;  # 改成你的 IP

  location /static {
    alias /root/django_project/django4blog/collected_static;
  }

  location / {
    proxy_set_header Host $host;
    proxy_pass http://unix:/tmp/39.107.240.223.socket;  # 改成你的 IP
  }
}

 :wq After saving and exiting, enter the command

sudo ln -s /etc/nginx/sites-available/django4blog /etc/nginx/sites-enabled

Then check the user information of Nginx configuration file:

Change this user name root, otherwise a 403 permission error may be reported.

cd /etc/nginx# , vi nginx.confchange the user to root

Finally refresh the Nginx configuration information:

sudo service nginx reload

Prepare backend users and enable Gunicorn

First go back to the directory where the project is located , enter the virtual environment , and enter the command to create a super account:cd django_project/django4blog

python manage.py createsuperuser

Then install gunicorn:

pip3 install gunicorn

Start it gunicornand change it to your own public network address and your own project name.

gunicorn --bind unix:/tmp/39.107.240.223.socket django4blog.wsgi:application

Test and run

Return to the local system and enter the address in the browser: homepage

Running successfully! !

Then we log in to the backend Log in | Django site admin and add a few pieces of data.

back to the homepage

Read article details page

Guess you like

Origin blog.csdn.net/agelee/article/details/127787103