本文將介紹如何在Linux上部署Django + Mysql + Apache環境。我們知道,Django內置的http伺服器只能工作在單線程下,做開發和調試時候是可以的,但是生產環境通常都會有多用戶併發,而且django的simple HTTP server處理大量靜態文件的性能太差,所以要用ap ...
本文將介紹如何在Linux上部署Django + Mysql + Apache環境。我們知道,Django內置的http伺服器只能工作在單線程下,做開發和調試時候是可以的,但是生產環境通常都會有多用戶併發,而且django的simple HTTP server處理大量靜態文件的性能太差,所以要用apache做前端。Django自帶的SQLite資料庫許可權只依賴於文件系統,沒有用戶帳戶的概念,這裡我們使用典型的關係型資料庫Mysql。看似簡單的環境搭建,在實際操作過程中還是遇到了不少的大坑,所以特地將過程記錄下來,也希望對大家有小小的幫助。
CentOS 7.5 + python 2.7.5 + Django 1.11.14 + Apache 2.4.6 + Mysql 5.7.23
1. 安裝Django
Linux上我們可以直接使用pip安裝Django
1.1 安裝python(使用CentOS 7.5自帶的python即可)
[root@localhost ~]# python --version Python 2.7.5
1.2 網上下載get-pip.py文件安裝pip:
wget https://bootstrap.pypa.io/get-pip.py
1.3 pip安裝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. 安裝Apache
Linux上使用yum安裝Apache即可
[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)
註意:使用yum安裝的httpd,其安裝目錄位於/etc/httpd/,我們只需要配置/etc/httpd/conf/httpd.conf即可
3. 安裝Mysql
我們使用yum安裝Mysql,需要先更新yum源
[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
[root@localhost ~]# yum install mysql-community-devel
註意:yum安裝的Mysql其文件目錄如下
- 配置文件:/etc/my.cnf
- 日誌文件:/var/log/mysqld.log
- 服務啟動腳本:/usr/lib/systemd/system/mysqld.service
- socket文件:/var/run/mysqld/mysqld.pid
4. 配置(重點)
以上三步都非常容易,但是將這三個環境配置好,還是費了我不少的時間...
4.1 配置Mysql
[root@localhost ~]# systemctl start mysqld # 開啟Mysql服務後,會為root設置一個預設密碼,我們首先重置密碼 # 獲得預設密碼 [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'; # 重置密碼後,我們創建一個資料庫,因為後續django連接Mysql時需要輸入資料庫名稱 mysql> create database Platform default charset=utf8; Query OK, 1 row affected (0.00 sec) mysql> quit Bye
4.2 django中配置Mysql
django中關於Mysql的配置:
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', } }
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")
補充:
關於 Error loading MySQLdb module: No module named MySQLdb
--> yum install MySQL-python
4.3 配置Apache
重點:安裝mod_wsgi
[root@localhost ~]# yum install mod_wsgi [root@localhost ~]# rpm -qa | grep wsgi mod_wsgi-3.4-12.el7_0.x86_64
編輯配置文件 /etc/httpd/conf/httpd.conf
ServerRoot "/etc/httpd" # 設定Apache監聽的埠號,可以設定多個 Listen 80 # 重點:這句是載入剛剛安裝的wsgi模塊,有了它django才能部署到Apache上,切記!!! 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 # 我們在/etc/httpd/conf/下新建httpd-vhosts.conf虛擬主機配置文件,完成對80埠的配置 # 這句是告訴Apache去調用httpd-vhosts.conf # 虛擬主機中的配置參數將覆蓋httpd.conf主配置文件中的設定 Include conf/httpd-vhosts.conf
虛擬主機配置文件(關鍵一步)
<VirtualHost *:80> ServerAdmin [email protected] 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" # 一定要定義python-path到項目目錄,否則會報出相關模塊無法找到的錯誤,切記!!! WSGIDaemonProcess samlinux01-platform.com python-path=/home/python_projects/Platform:/usr/lib64/python2.7/site-packages WSGIProcessGroup samlinux01-platform.com WSGIScriptReloading On # 設定Apache訪問django的項目目錄 Alias /static /home/python_projects/Platform/static Alias /media /home/python_projects/Platform/media
# 註意:將python中django admin的靜態文件鏈接到static目錄下,否則會出現登錄django admin靜態文件404的問題
# ln -s /usr/lib64/python2.7/site-packages/django/contrib/admin/static/admin admin
<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>
註意:每次編輯完成後都需要重啟httpd服務使配置生效
[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
編輯django中的 wsgi.py文件
""" 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() # 添加項目路徑到python的環境變數中 # For Apache server import sys project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, project_dir)
至此,大功告成,我們直接可以通過80埠訪問我們的項目,雖然上面的步驟簡單,但是網上查的資料並沒有特別詳細完整的,中間還是走了不少的彎路,所以特意將配置步驟記錄下來,方便後續再次配置!