This article describes how to deploy the Django + Mysql + Apache environment on Linux. We know that Django's built-in http server can only work in a single thread. It is possible to do development and debugging, but the production environment usually has multi-user concurrency, and the performance of django's simple HTTP server for handling a large number of static files is too poor, so apache is used as the front-end. Django's own SQLite database privileges depend only on the file system, without the concept of user accounts. Here we use Mysql, a typical relational database. Seemingly simple environment construction, in the actual operation process or encountered a lot of pits, so the process is specially recorded, but also hope to help you a little.
CentOS 7.5 + python 2.7.5 + Django 1.11.14 + Apache 2.4.6 + Mysql 5.7.23
1. Install Django
On Linux, we can install Django directly using pip
1.1 Install Python (use the python that comes with CentOS 7.5)
[root@localhost ~]# python --version Python 2.7.5
1.2 Download the get-pip.py file online to install pip:
wget https://bootstrap.pypa.io/get-pip.py
1.3 pip installation django
[root@localhost ~]# pip install django [root@localhost ~]# python Python 2.7.5 (default, Jul 13 2018, 13:06:57) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.get_version() '1.11.14'
2. Install Apache
Install Apache on Linux using yum
[root@localhost ~]# yum install httpd [root@localhost ~]# httpd -V [Thu Aug 16 20:57:04.487586 2018] [so:warn] [pid 1605] AH01574: module wsgi_module is already loaded, skipping Server version: Apache/2.4.6 (CentOS) Server built: Jun 27 2018 13:48:59 Server's Module Magic Number: 20120211:24 Server loaded: APR 1.4.8, APR-UTIL 1.5.2 Compiled using: APR 1.4.8, APR-UTIL 1.5.2 Architecture: 64-bit Server MPM: prefork threaded: no forked: yes (variable process count)
Note: The installation directory of httpd installed with yum is located at / etc/httpd /. We only need to configure / etc/httpd/conf/httpd.conf.
3. Install Mysql
We use Yum to install Mysql. We need to update the yum source first.
[root@localhost ~]# wget http://dev.mysql.com/get/mysql57-community-release-el7-8.noarch.rpm [root@localhost ~]# rpm -ivh mysql57-community-release-el7-8.noarch.rpm [root@localhost ~]# yum install mysql-community-server
Note: The file directory of Mysql installed by yum is as follows
- Configuration file: / etc/my.cnf
- Log file: / var/log/var/log/mysqld.log
- Service startup script: / usr / lib / system D / system / mysqld.
- socket file: / var/run/mysqld/mysqld.pid
4. Configuration (emphasis)
The above three steps are very easy, but it took me a lot of time to configure these three environments well.
4.1 Configure Mysql
[root@localhost ~]# systemctl start mysqld # When the Mysql service is turned on, a default password is set for root. Let's reset the password first. # Get the default password [root@localhost ~]# cat /var/log/mysqld.log | grep -i password [root@localhost ~]# mysql -uroot -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 8 Server version: 5.7.23 MySQL Community Server (GPL) mysql>ALTER USER 'root'@'localhost' IDENTIFIED BY 'Sam_tech_0912'; # After resetting the password, we create a database because subsequent django connections to Mysql require the database name to be entered. mysql> create database Platform default charset=utf8; Query OK, 1 row affected (0.00 sec) mysql> quit Bye
4.2 Configure Mysql in django
Configuration of Mysql in django:
DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Platform', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'Sam_tech_0912', } }
Configuration of other parts of django:
DEBUG = True ALLOWED_HOSTS = ["*",] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates"),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media")
4.3 Configuration of Apache
Focus: Installing mod_wsgi
[root@localhost ~]# yum install mod_wsgi [root@localhost ~]# rpm -qa | grep wsgi mod_wsgi-3.4-12.el7_0.x86_64
Edit the configuration file/etc/httpd/conf/httpd.conf
ServerRoot "/etc/httpd" # Setting the port number that Apache listens on, you can set more than one Listen 80 # Emphasis: This sentence is to load the newly installed wsgi module, with which django can be deployed to Apache, remember!!! LoadModule wsgi_module modules/mod_wsgi.so Include conf.modules.d/*.conf User apache Group apache ServerAdmin root@localhost ServerName localhost:80 <Directory /> AllowOverride none Require all denied </Directory> DocumentRoot "/var/www/html" <Directory "/var/www"> AllowOverride None Require all granted </Directory> <Directory "/var/www/html"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <IfModule dir_module> DirectoryIndex index.html </IfModule> <Files ".ht*"> Require all denied </Files> ErrorLog "logs/error_log" LogLevel warn <IfModule log_config_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common <IfModule logio_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio </IfModule> CustomLog "logs/access_log" combined </IfModule> <IfModule alias_module> ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" </IfModule> <Directory "/var/www/cgi-bin"> AllowOverride None Options None Require all granted </Directory> <IfModule mime_module> TypesConfig /etc/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz AddType text/html .shtml AddOutputFilter INCLUDES .shtml </IfModule> AddDefaultCharset UTF-8 <IfModule mime_magic_module> MIMEMagicFile conf/magic </IfModule> EnableSendfile on IncludeOptional conf.d/*.conf # We create a new httpd-vhosts.conf virtual host configuration file under / etc/httpd/conf/, and complete the configuration of port 80. # This sentence tells Apache to call httpd-vhosts.conf # The configuration parameters in the virtual host will override the settings in the httpd.conf master configuration file Include conf/httpd-vhosts.conf
Virtual Host Profile (Key Step)
<VirtualHost *:80> ServerAdmin samliuming@aliyun.com DocumentRoot "/home/python_projects/Platform" ServerName samlinux01-platform.com ServerAlias sam-platform.com ErrorLog "logs/platform_error.log" CustomLog "logs/platform_access.log" common WSGIScriptAlias / "/home/python_projects/Platform/Platform/wsgi.py" # Be sure to define python-path To the project catalog, otherwise it will report errors that related modules can not find, remember!!! WSGIDaemonProcess samlinux01-platform.com python-path=/home/python_projects/Platform WSGIProcessGroup samlinux01-platform.com WSGIScriptReloading On # Set Apache's project directory for accessing django Alias /static /home/python_projects/Platform/static Alias /media /home/python_projects/Platform/media <Directory /home/python_projects/Platform/media> AllowOverride None Options Indexes FollowSymLinks Require all granted </Directory> <Directory /home/python_projects/Platform/static> AllowOverride None Options Indexes FollowSymLinks Require all granted </Directory> <Directory /home/python_projects/Platform/Platform> <Files wsgi.py> AllowOverride None Require all granted </Files> </Directory> </VirtualHost>
Note: The httpd service needs to be restarted after each edit is completed to make the configuration effective
[root@localhost ~]# httpd -t [Thu Aug 16 20:35:06.439115 2018] [so:warn] [pid 1520] AH01574: module wsgi_module is already loaded, skipping Syntax OK [root@localhost ~]# systemctl restart httpd.service
Edit the wsgi.py file in django
""" WSGI config for Platform project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Platform.settings") application = get_wsgi_application() # Add project path to python In environmental variables # For Apache server import sys project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, project_dir)