Cenos7環境下部署使用docker部署 django+apache+mod_wsgi環境php
1、系統要求html
1.前提環境:必須是centos7的系統python
2.安裝dockermysql
yum install -y yum-utils \
device-mapper-persistent-data \
lvm2
yum-config-manager \
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo
yum install docker-ce docker-ce-cli containerd.io
3.安裝docker-compose linux
(1)獲取並安裝
sudo curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
(2)增長執行權限
sudo chmod +x /usr/local/bin/docker-compose
(3)查看版本
$ docker-compose --version
docker-compose version 1.24.1, build 1110ad01
nginx
4.啓動docker前,配置國內docker倉庫源
在/etc/docker/ 目錄下新建 daemon.json文件
/etc/docker/daemon.json
編輯內容爲:
{
"registry-mirrors": ["https://XXXX.mirror.aliyuncs.com"]
}
5.啓動dockerc++
(1)加入開機啓動項
systemct enable docker
(2)啓動docker
systemct start docker
2、項目目錄結構介紹git
項目目錄結構圖解github
3、重要配置說明(重點)web
1.構建django+apache環境的鏡像Dockerfile文件
FROM centos:7.6.1810
#安裝依賴和httpd服務yum clean all && yum makecache && yum install epel-release -y --nogpgcheck &&
#RUN yum groupinstall "Development tools" -y --nogpgcheck && \
RUN yum install -y --nogpgcheck gcc make gcc-c++ \
libffi-devel \
zlib-devel \
bzip2-devel \
openssl-devel \
ncurses-devel \
zx-devel \
sqlite-devel \
readline-devel \
tk-devel \
gdbm-devel \
db4-devel \
libpcap-devel \
httpd httpd-devel
#設定容器內的工做路徑
WORKDIR /usr/local/src/django/resource
#從宿主機拷貝相關文件至容器/usr/local/src/django/resource路徑
COPY resource ./
#編譯安裝python3.7.4以及配置pip安裝源
RUN tar xvf Python-3.7.4.tar.xz && cd Python-3.7.4 && \
./configure --prefix=/usr/local/python3 --enable-optimizations --enable-shared && \
make && make install && \
#建立python3.7的軟連接python3
ln -s /usr/local/python3/bin/python3.7 /usr/bin/python3 && \
ln -s /usr/local/python3/bin/pip3.7 /usr/bin/pip3 && \
#編譯安裝完成後,添加python動態連接庫信息配置文件,並讓系統從新加載動態庫配置文件
echo "/usr/local/python3/lib/" > /etc/ld.so.conf.d/python3.conf && ldconfig && \
#設置pip安裝方式的國內源
mkdir -p /root/.pip/ && mv /usr/local/src/django/resource/pip.conf /root/.pip/pip.conf && \
pip3 install --upgrade pip && \
pip3 install virtualenv && \
#編譯安裝mod_wsgi,注意指明python路徑
#使用python3.7編譯,必定是python3.7,否則後面會報錯。(填寫你本身的Python3 路徑)
cd /usr/local/src/django/resource && \
tar xvfz mod_wsgi-4.6.5.tar.gz && cd mod_wsgi-4.6.5 && \
./configure -with-apxs=/usr/bin/apxs --enable-shared --with-python=/usr/local/python3/bin/python3.7 && make && make install && \
yum clean all
#設定Django項目工做路徑
WORKDIR /var/www/html/django/
#pip方式安裝各類包和xadmin
RUN pip3 --no-cache-dir install -r /usr/local/src/django/resource/requirements.txt && \
pip3 --no-cache-dir install /usr/local/src/django/resource/xadmin-django2.zip && \
chmod -R 755 /var/www/html && \
chown -R apache:apache /var/www/html
#Systemd環境---刪除可能致使問題的許多單元文件後,才能啓動httpd服務
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*; \
systemctl enable httpd.service
#暴露相關端口
EXPOSE 80 8080
VOLUME [ "/sys/fs/cgroup" ]
#啓動systemd,若沒有此命令,會致使沒法啓動httpd服務
CMD ["/usr/sbin/init"]
pip.conf文件配置內容:
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host=pypi.tuna.tsinghua.edu.cn
注意:linux系統pip.conf文件放置於 /root/.pip/下
2.docker-compose單機容器編排文件配置
version: '3'
services:
### Django container #########################################
django:
build:
context: ./build/django
args:
TIME_ZONE: ${GLOBAL_TIME_ZONE}
CHANGE_SOURCE: ${GLOBAL_CHANGE_SOURCE}
ports:
- "80:80"
- "8080:8080"
- "8081:8081"
volumes:
- ${PROJECT_FOLDER}/:/var/www/html/django/:rw
- ./work/components/httpd/conf/httpd.conf:/etc/httpd/conf/httpd.conf:rw
- ./work/components/httpd/conf.d/django.conf:/etc/httpd/conf.d/django.conf:rw
restart: always
privileged: true
networks:
net-django:
ipv4_address: 10.127.3.3
### MariaDB container #########################################
mariadb:
image: mariadb:10.4.7
ports:
- "${MYSQL_PORT}:3306"
volumes:
- ./work/components/mariadb/data:/var/lib/mysql:rw
- ./work/components/mariadb/config/mysql.cnf:/etc/mysql/conf.d/mysql.cnf:rw
- ./work/components/mariadb/log:/var/log/mysql:rw
restart: always
privileged: true
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_PASSWORD}
networks:
net-django:
ipv4_address: 10.127.3.2
networks:
net-django:
ipam:
config:
- subnet: 10.127.3.0/24
3.apache配置文件
(1)主配置 /etc/httpd/conf/httpd.conf
在末尾部分引入mod_wsgi模塊
#LoadModule wsgi_module "/usr/lib64/httpd/modules/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so"
LoadModule wsgi_module "/usr/lib64/httpd/modules/mod_wsgi.so"
# # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so 'log/access_log' # with ServerRoot set to '/www' will be interpreted by the # server as '/www/log/access_log', where as '/log/access_log' will be # interpreted as '/log/access_log'. # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # Do not add a slash at the end of the directory path. If you point # ServerRoot at a non-local disk, be sure to specify a local disk on the # Mutex directive, if file-based mutexes are used. If you wish to share the # same ServerRoot for multiple httpd daemons, you will need to change at # least PidFile. # ServerRoot "/etc/httpd" # # Listen: Allows you to bind Apache to specific IP addresses and/or # ports, instead of the default. See also the <VirtualHost> # directive. # # Change this to Listen on specific IP addresses as shown below to # prevent Apache from glomming onto all bound IP addresses. # #Listen 12.34.56.78:80 Listen 80 # # Dynamic Shared Object (DSO) Support # # To be able to use the functionality of a module which was built as a DSO you # have to place corresponding `LoadModule' lines at this location so the # directives contained in it are actually available _before_ they are used. # Statically compiled modules (those listed by `httpd -l') do not need # to be loaded here. # # Example: # LoadModule foo_module modules/mod_foo.so # Include conf.modules.d/*.conf # # If you wish httpd to run as a different user or group, you must run # httpd as root initially and it will switch. # # User/Group: The name (or #number) of the user/group to run httpd as. # It is usually good practice to create a dedicated user and group for # running httpd, as with most system services. # User apache Group apache # 'Main' server configuration # # The directives in this section set up the values used by the 'main' # server, which responds to any requests that aren't handled by a # <VirtualHost> definition. These values also provide defaults for # any <VirtualHost> containers you may define later in the file. # # All of these directives may appear inside <VirtualHost> containers, # in which case these default settings will be overridden for the # virtual host being defined. # # # ServerAdmin: Your address, where problems with the server should be # e-mailed. This address appears on some server-generated pages, such # as error documents. e.g. admin@your-domain.com # ServerAdmin root@localhost # # ServerName gives the name and port that the server uses to identify itself. # This can often be determined automatically, but we recommend you specify # it explicitly to prevent problems during startup. # # If your host doesn't have a registered DNS name, enter its IP address here. # #ServerName www.example.com:80 # # Deny access to the entirety of your server's filesystem. You must # explicitly permit access to web content directories in other # <Directory> blocks below. # <Directory /> AllowOverride none Require all granted </Directory> # # Note that from this point forward you must specifically allow # particular features to be enabled - so if something's not working as # you might expect, make sure that you have specifically enabled it # below. # # # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # DocumentRoot "/var/www/html" # # Relax access to content within /var/www. # <Directory "/var/www"> AllowOverride None # Allow open access: Require all granted </Directory> # Further relax access to the default document root: <Directory "/var/www/html"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride None # # Controls who can get stuff from this server. # Require all granted </Directory> # # DirectoryIndex: sets the file that Apache will serve if a directory # is requested. # <IfModule dir_module> DirectoryIndex index.html </IfModule> # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # <Files ".ht*"> Require all denied </Files> # # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a <VirtualHost> # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a <VirtualHost> # container, that host's errors will be logged there and not here. # ErrorLog "logs/error_log" # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn <IfModule log_config_module> # # The following directives define some format nicknames for use with # a CustomLog directive (see below). # 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> # You need to enable mod_logio.c to use %I and %O LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio </IfModule> # # The location and format of the access logfile (Common Logfile Format). # If you do not define any access logfiles within a <VirtualHost> # container, they will be logged here. Contrariwise, if you *do* # define per-<VirtualHost> access logfiles, transactions will be # logged therein and *not* in this file. # #CustomLog "logs/access_log" common # # If you prefer a logfile with access, agent, and referer information # (Combined Logfile Format) you can use the following directive. # CustomLog "logs/access_log" combined </IfModule> <IfModule alias_module> # # Redirect: Allows you to tell clients about documents that used to # exist in your server's namespace, but do not anymore. The client # will make a new request for the document at its new location. # Example: # Redirect permanent /foo http://www.example.com/bar # # Alias: Maps web paths into filesystem paths and is used to # access content that does not live under the DocumentRoot. # Example: # Alias /webpath /full/filesystem/path # # If you include a trailing / on /webpath then the server will # require it to be present in the URL. You will also likely # need to provide a <Directory> section to allow access to # the filesystem path. # # ScriptAlias: This controls which directories contain server scripts. # ScriptAliases are essentially the same as Aliases, except that # documents in the target directory are treated as applications and # run by the server when requested rather than as documents sent to the # client. The same rules about trailing "/" apply to ScriptAlias # directives as to Alias. # ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" </IfModule> # # "/var/www/cgi-bin" should be changed to whatever your ScriptAliased # CGI directory exists, if you have that configured. # <Directory "/var/www/cgi-bin"> AllowOverride None Options None Require all granted </Directory> <IfModule mime_module> # # TypesConfig points to the file containing the list of mappings from # filename extension to MIME-type. # TypesConfig /etc/mime.types # # AddType allows you to add to or override the MIME configuration # file specified in TypesConfig for specific file types. # #AddType application/x-gzip .tgz # # AddEncoding allows you to have certain browsers uncompress # information on the fly. Note: Not all browsers support this. # #AddEncoding x-compress .Z #AddEncoding x-gzip .gz .tgz # # If the AddEncoding directives above are commented-out, then you # probably should define those extensions to indicate media types: # AddType application/x-compress .Z AddType application/x-gzip .gz .tgz # # AddHandler allows you to map certain file extensions to "handlers": # actions unrelated to filetype. These can be either built into the server # or added with the Action directive (see below) # # To use CGI scripts outside of ScriptAliased directories: # (You will also need to add "ExecCGI" to the "Options" directive.) # #AddHandler cgi-script .cgi # For type maps (negotiated resources): #AddHandler type-map var # # Filters allow you to process content before it is sent to the client. # # To parse .shtml files for server-side includes (SSI): # (You will also need to add "Includes" to the "Options" directive.) # AddType text/html .shtml AddOutputFilter INCLUDES .shtml </IfModule> # # Specify a default charset for all content served; this enables # interpretation of all content as UTF-8 by default. To use the # default browser choice (ISO-8859-1), or to allow the META tags # in HTML content to override this choice, comment out this # directive: # AddDefaultCharset UTF-8 <IfModule mime_magic_module> # # The mod_mime_magic module allows the server to use various hints from the # contents of the file itself to determine its type. The MIMEMagicFile # directive tells the module where the hint definitions are located. # MIMEMagicFile conf/magic </IfModule> # # Customizable error responses come in three flavors: # 1) plain text 2) local redirects 3) external redirects # # Some examples: #ErrorDocument 500 "The server made a boo boo." #ErrorDocument 404 /missing.html #ErrorDocument 404 "/cgi-bin/missing_handler.pl" #ErrorDocument 402 http://www.example.com/subscription_info.html # # # EnableMMAP and EnableSendfile: On systems that support it, # memory-mapping or the sendfile syscall may be used to deliver # files. This usually improves server performance, but must # be turned off when serving from networked-mounted # filesystems or if support for these functions is otherwise # broken on your system. # Defaults if commented: EnableMMAP On, EnableSendfile Off # #EnableMMAP off EnableSendfile on AcceptFilter http none AcceptFilter https none # Supplemental configuration # # Load config files in the "/etc/httpd/conf.d" directory, if any. IncludeOptional conf.d/*.conf #LoadModule wsgi_module "/usr/lib64/httpd/modules/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so" LoadModule wsgi_module "/usr/lib64/httpd/modules/mod_wsgi.so"
(2) 虛擬主機配置
#python3編譯安裝路徑 WSGIPythonHome "/usr/local/python3/" #Listen 80 在主配置文件httpd.conf中已監聽此端口,此處再也不須要監聽 <VirtualHost *:80> ServerName localhost #定義項目靜態文件位置 Alias /static /var/www/html/django/hos/static <Directory /var/www/html/django/hos/static> Require all granted </Directory> #定義項目wsgi.py文件位置 <Directory /var/www/html/django/hos/hos/> <Files wsgi.py> Require all granted </Files> </Directory> #python3第三方庫路徑 WSGIDaemonProcess hos python-path=/usr/local/python3/lib/python3.7/site-packages #Django項目的wsgi文件位置 WSGIScriptAlias / /var/www/html/django/hos/hos/wsgi.py Errorlog logs/error_log_hos </VirtualHost>
4.mariadb數據庫配置文件
# The MySQL Client configuration file.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html
[mysql]
[mysqld]
sql-mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
innodb_force_recovery = 1
character-set-server=utf8
explicit_defaults_for_timestamp=true
5.Django項目文件配置 setting.py文件
(1)數據庫配置
DATABASES = {
'default': {
# 鏈接的數據庫類型
'ENGINE': 'django.db.backends.mysql',
# 數據庫的地址(容器mariadb的IP地址)
'HOST': '10.127.3.2',
# 數據庫使用的端口
'PORT': '3306',
# 所鏈接的數據庫名字
'NAME': 'book',
# 鏈接數據庫的用戶名
'USER': 'root',
# 鏈接數據庫的密碼
'PASSWORD': 'DockerLNMP'
}
}
(2)靜態文件路徑
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
6.更改項目目錄下 wsgi.py文件配置
import os
import sys #新導入sys
from django.core.wsgi import get_wsgi_application
sys.path.append("/var/www/html/django/book") #新增項目路徑
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "book.settings")
os.environ["DJANGO_SETTINGS_MODULE"] = "book.settings" #將上面更改成此配置
application = get_wsgi_application()
4、啓動項目
(1)docker-compose各命令參數
docker-compose up -d 構建並後臺啓動容器
docker-compose exec nginx bash 登陸到nginx容器中
docker-compose down 刪除全部nginx容器,鏡像
docker-compose ps 顯示全部容器
docker-compose restart nginx 從新啓動nginx容器
docker-compose run --no-deps --rm php-fpm php -v 在php-fpm中不啓動關聯容器,並容器執行php -v 執行完成後刪除容器
docker-compose build nginx 構建鏡像 。
docker-compose build --no-cache nginx 不帶緩存的構建。
docker-compose logs nginx 查看nginx的日誌
docker-compose logs -f nginx 查看nginx的實時日誌
docker-compose config -q 驗證(docker-compose.yml)文件配置,當配置正確時,不輸出任何內容,當文件配置錯誤,輸出錯誤信息。
docker-compose events --json nginx 以json的形式輸出nginx的docker日誌
docker-compose pause nginx 暫停nignx容器
docker-compose unpause nginx 恢復ningx容器
docker-compose rm nginx 刪除容器(刪除前必須關閉容器)
docker-compose stop nginx 中止nignx容器
docker-compose start nginx 啓動nignx容器