Docker部署Django+apache+mod_wsgi环境

Cenos7环境下部署使用docker部署 django+apache+mod_wsgi环境

一、系统要求

1.前提环境:必须是centos7的系统

2.安装docker

  • 安装依赖库文件  yum install -y yum-utils device-mapper-persistent-data lvm2
    yum install -y yum-utils \
      device-mapper-persistent-data \
      lvm2
  • 安装docker稳定的库文件  yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
     yum-config-manager \
        --add-repo \
        https://download.docker.com/linux/centos/docker-ce.repo
  • 安装docker   yum install docker-ce docker-ce-cli containerd.io
    yum install docker-ce docker-ce-cli containerd.io

3.安装docker-compose 

(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

 


4.启动docker前,配置国内docker仓库源

在/etc/docker/ 目录下新建 daemon.json文件
/etc/docker/daemon.json

编辑内容为:

{
"registry-mirrors": ["https://XXXX.mirror.aliyuncs.com"]
}

 

 

5.启动docker

(1)加入开机启动项
systemctl enable docker

(2)启动docker
systemctl start docker

 

二、项目目录结构介绍

 项目目录结构图解

 

 三、重要配置说明(重点)

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"
完整版httpd.conf

 

(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()

 

 

四、启动项目

(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容器

 

 

 

 

 

 

 

 
posted @ 2019-09-11 16:18  %华&仔%  阅读(426)  评论(0编辑  收藏