python3.6+unbuntu+apache2+django+virtualenv 一文搞定服务器部署

基本配置

  • 阿里云服务器
  • unbuntu
  • virtualenv
  • python3.6
  • apache2
  • Adjango

配置python环境

安装 python、pip

sudo apt-get update

  1. sudo apt-get install python3.6

    • 未找到资源
      • sudo apt-get install software-properties-common python-software-properties
      • sudo add-apt-repository ppa:deadsnakes/ppa
      • sudo apt-get update
      • sudo apt-get install python3.6
    • 下载速度过慢:换源
  2. curl https://bootstrap.pypa.io/ez_setup.py -o - | python3.6 && python3.6 -m easy_install pip
  3. pip install --upgrade pip

  4. python --version && pip --version检验版本

安装 virtualenv

  1. pip install virtualenv
  2. pip install virtualenvwrapper
  3. export WORKON_HOME=$HOME/.virtualenvs
  4. mkdir -p $WORKON_HOME
  5. vim ~/.bashrc,底部加入下面两行后,source ~/.bashrc
    • export WORKON_HOME=$HOME/.virtualenvs
    • source /usr/local/bin/virtualenvwrapper.sh
  6. 尝试 lsvirtualenv 看是否安装成功
    • 如果没有找到该命令
    • find / -name virtualenvwrapper.sh,结果替换/usr/local/bin/virtualenvwrapper.sh再执行上述操作

~/.bashrc会在每次登陆当前用户时自动执行,设置虚拟环境保存目录WORKON_HOME

因此,使用其他用户登陆则需要手动执行上述命令来设置环境变量。

virtualenvs 使用详见:https://virtualenv.pypa.io/en/latest/

配置python虚拟环境

  1. 创建:mkvirtualenv --python=python3.6 your_env_name
  2. django:pip install django
  3. 安装第三方库

配置 apache2

安装 apache2

  1. sudo apt-get install apache2:安装apache2服务,注意观察是否存在 perl: warning: Falling back to a fallback locale异常,需要解决

    perl: warning: Setting locale failed.
    perl: warning: Please check that your locale settings:
     LANGUAGE = (unset),
     LC_ALL = (unset),
     LC_CTYPE = "zh_CN.UTF-8",
     LC_TERMINAL_VERSION = "3.3.1",
     LC_TERMINAL = "iTerm2",
     LANG = "en_US.UTF-8"
        are supported and installed on your system.
    perl: warning: Falling back to a fallback locale ("en_US.UTF-8").
    • vim ~/.bashrc->最底部增加export LC_ALL=en_US.UTF-8en_US.UTF-8需和报错信息说明的一致。
    • source ~/.bashrc重新加载环境变量
    • 注意,/.bashrc会在每次登陆当前用户时执行,但是其他用户不会执行该文件,即只能在当前用户下正常使用 apache2。
  2. sudo apt-get install apache2-dev:安装 apache2 开发工具

该环节也可采取从官网下载源码编译安装的方式。

安装 mod-wsgi 服务

若使用 python3.5 可直接 sudo apt install libapache2-mod-wsgi-py3 ,是以 python3.5编译好的,不需要以下安装步骤。

安装步骤来自官方文档:https://modwsgi.readthedocs.io/en/develop/user-guides/quick-installation-guide.html#apache-requirements

依赖项:

  1. sudo apt-get install apache2-dev:安装 apache2 开发工具,如果是以源码编译安装的 apache2,则可省略该步骤。apt-get 安装的 apache2 不包含开发工具。
  2. sudo apt-get install python3.6-dev:若使用其他版本的python注意调整该命令

正式安装:

  1. wget https://codeload.github.com/GrahamDumpleton/mod_wsgi/tar.gz/4.5.24:可访问官方,根据需要下载目标版本,下载内容为源码压缩包
  2. tar zxvf 4.5.24 && cd mod_wsgi-4.5.24:解压并进入
  3. 配置参数,可参考官方文档获取细节
    • --with-apxs:编译工具的地址,不设置则会自动在默认位置搜索。可先不设置尝试编译安装,若出错再根据平台(unbuntu、debian)查找位置
      • find / -name '*apxs*' -print:检索当前目录下是否含 apxs
    • --with-python:指示编译对应的python版本,注意编译使用的python版本必须和后面网站执行使用的版本完全相同,最好在同一路径!可参考下例
      • 没有使用虚拟环境或conda的:./configure --with-apxs=/usr/local/apache24/bin/apxs --with-python=/usr/local/python36/bin/python3.6
      • 使用虚拟环境的:./configure --with-python=/home/XXX/.virtualenvs/env_name/bin/python3.6
  4. make && make install:权限不足请登录 root 用户或前加 sudo
    • 安装成功
      • 最后一行打印类似 chmod 644 /usr/lib/apache2/modules/mod_wsgi.so
      • 请复制粘贴执行之 sudo chmod 644 /usr/lib/apache2/modules/mod_wsgi.so
    • 安装失败:make clean 后google一下。
  5. 登记 mod_wsgi.soapache2
    • unbuntu
      • sudo vim /atc/apache2/apache.conf
      • 最后一行写入 LoadModule wsgi_module 刚刚打印出的mod_wsgi.so绝对路径
    • Other platform
      • 只是 conf 文件位置和名称不同(有的叫 http.conf),请自行google,,仍然是最后一行写入相同内容
  6. 加载 apache2 ,查看是否存在异常
    • sudo service apache2 restart or sudo service apache2 start
    • 本地端访问公网ip,应该存在正常的 apache 欢迎页

部署django项目

up to server

  1. 上传项目至服务器

  2. (可选) 重置项目:测试时产生的数据库以及迁移记录。慎重!

    • rm db.sqlite3
    • rm -rf */migrations/
  3. 迁移

    • 执行:python manage.py migrate
    • 检查:python manage.py makemigrations
    • 详细说明官方文档:https://docs.djangoproject.com/zh-hans/3.0/ref/django-admin/
  4. (可选) 创建管理账号

    • python manage.py createsuperuser
  5. 测试

    • settings.py:DEBUG=True
    • workon your_env
    • python manage.py runserver ).0.0.0:8000
    • 本地端访问公网ip,应该能正常运行
  6. django 部署静态文件

    • 参考自:https://docs.djangoproject.com/zh-hans/3.0/howto/deployment/wsgi/modwsgi/

    • django设置:settings.py

      • STATIC_ROOT:执行 python manage.py collectstatic 后,STATICFILES_FINDERS找到的文件将被拷贝到该目录下

      • STATIC_URL:用户以URL:ip:port/path?key=a&key=...访问时,处于path开头的 $STATIC_URL部分将按照 apache_site.conf进行替换得到服务器上的绝对路径。apache_site.conf的配置在下一环节介绍。这种替换完全是服务器框架的操作,和django无关。非 apache2 框架也有类似的设置方式。

      • STATICFILES_DIRS:一个目录列表,如果在STATICFILES_FINDERS中设置 'django.contrib.staticfiles.finders.FileSystemFinder'则被STATICFILES_FINDERS找到。

      • STATICFILES_FINDERS:按规则查找静态文件

        [
        # STATICFILES_DIRS
            'django.contrib.staticfiles.finders.FileSystemFinder',
        # $(APPs_path)/static
            'django.contrib.staticfiles.finders.AppDirectoriesFinder',
        ]
      • 详见:https://docs.djangoproject.com/zh-hans/3.0/ref/settings/#std:setting-STATIC_ROOT

    • python manage.py collectstatic

      • STATICFILES_DIRS查找到的文件,复制到 STATIC_ROOT

撰写 apache2 网站配置文件


# 配置文件保存在 /etc/apache2/sites-available/
# /etc/apache2/sites-available/ 下新建你的网站文件 your-site-name.conf
# 在其中配置以下内容
# 指定 80 端口
<VirtualHost *:80>
    # 指定网站的地址(域名或者 IP 地址)
    # 该地址必须在 ALLOWED_HOSTS 列表中
    ServerName your_ip_addr
    # ServerAlias www.example1.com www.example2.com
    # ServerAdmin 0.0.0.0
    
    
    # Alias URL=schema://ip:port/path?中path的前缀 实际服务器地址
    # 该命令能够要求 apache2 自动对用户的访问 URL:path 进行转义
    # 这里保证和 django setting 中 一致,
    # 若 STATIC_URL='/static/' STATIC_ROOT='/var/static_root/',则如下
    Alias /static/ /var/static_root/
    # 同时设置目录权限
    <Directory /var/static_root>
        Require all granted
    </Directory>
    
    # 如果你还有其他文件夹需要转义,比如说存储视频的文件夹、或者存储你自定义内容的静态文件夹,都可以用这种方式来设置
    
    
    # 指定 wsgi.py 脚本位置,ajango 项目中自动创建的 wsgi.py 是和 mod_wsgi 的挂载点
    WSGIScriptAlias / /home/XXX/my_django_site/my_django_site/wsgi.py
    
    # "WSGIDaemonProcess" 是对守护进程的设置,具体参数参见 https://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGIDaemonProcess.html
    # 主要设置两个参数:
    # python-path: 冒号分割的目录,这里的内容将被加入到python的检索范围内
    # python-home:指明使用的python版本,需要指向包含 /bin/python 的目录,虚拟环境或直装python均适用
    WSGIDaemonProcess your_ip_addr python-home=/home/my_usr_name/.virtualenvs/my_env_name python-path=/home/my_usr_name/.virtualenvs/my_env_name/lib/python3.6/site-packages:other_path_you_like
    WSGIProcessGroup your_ip_addr
    # 如果你对这里的设置感到迷惑,非常推荐去阅读一下上述链接,官方文档说的非常详细
    # 还有其他功能比如说设置进程数等强大功能。
    
    
    <Directory /home/XXX/my_django_site/my_django_site>
    <Files wsgi.py>
        Require all granted
    </Files>
    </Directory>
    
</VirtualHost>

修改文件目录权限

Apache 默认运行网站的用户是 www-data,而我们在上述设置中使用并不是 www-data 所以需要修改项目文件、目录的权限,使得 Apache 能够对所需要的文件进行 RWX。

  1. 对 linux 权限的含义、权限的查询、权限的修改有一个基本的了解
    • 明白 rwx,明白目录需要x(执行)权限才能进入
    • 权限查询 ls -al
    • 权限修改命令
      • chmod: change modify
      • chgrp: change group
      • chown: change owner
  2. 正式开始修改(慎重!请对自己的操作负责)
# 请在理解下列命令的基础上修改、调整、执行

# 目录必须有 x 权限才能进入,因此需要可读可执行
# 一般文件需要可读的权限

sudo chmod -R 644 my_project
sudo find my_project -type d | xargs chmod 755


# 若存在上传目录,则需要可写的权限
sudo chgrp www-data my_project/upload
sudo chmod g+w my_project/upload




# sqlite3 会生成一个db.sqlite3文件,所以需要修改这个文件的权限,加上写的权限
sudo chgrp www-data my_project
sudo chmod g+w my_project
sudo chgrp www-data my_project/db.sqlite3 
sudo chmod g+w my_project/db.sqlite3

# 设置的 python-path python-home 或许也需要权限,根据你的设置,可先不设置,后面根据报错来调整


部署过程中出现的问题80%都与权限有关,每个平台、每个环境都有所不同,需要在理解权限的基础上根据后面的调试环境自行修正。

运行网站与调试

调试

vim django_site/django_site/settings.py:DEBUG = False

vim /var/log/apache2 查看日志

vim 快捷指令:

  • 重新加载 esc :e enter
  • 跳转到尾部 shift+g

运行

# 配置文件设置在 /etc/apache2/sites-available/ 目录下,这里只写名字,可在任何目录下执行
sudo a2ensite my_site.conf
sudo service apache2 reload
sudo service apache2 restart


err:
Invalid command 'WSGIScriptAlias', perhaps misspelled or defined by a module not included in the server configuration

WSGIScriptAlias有问题的原因通常是 mod-wsgi 安装有问题
检查 export LC_ALL=en_US.UTF-8
注意~/.bashrc 只针对当前用户有效


err:
[Thu Feb 13 15:17:10.020824 2020] [wsgi:error] [pid 25702:tid 140038272866048] [remote 1.194.132.43:44]     from django.core.wsgi import get_wsgi_application
[Thu Feb 13 15:17:10.020840 2020] [wsgi:error] [pid 25702:tid 140038272866048] [remote 1.194.132.43:44] ImportError: No module named 'django'

首先检查 conf 文件中的python-path 是否配置正确,如果正确,则检查其下的权限是否正确,即路径目录均rx,所有文件均r


err:
由于apache2 默认 挂载点是 '/' 因此在代码中写的相对路径将以该点重新计算,可能造成错误。

其他

服务器重置完后,之前配置的ssh秘钥失效,本地端无法访问服务器

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
SHA256:ONuB9t+zfCAiryLoQ7eYnVE2FnG4IoH/hP4MMYGgOMY.
Please contact your system administrator.
Add correct host key in /Users/XXX/.ssh/known_hosts to get rid of this message.
Offending RSA key in /Users/XXX/.ssh/known_hosts:2
ECDSA host key for X.X.X.X has changed and you have requested strict checking.
Host key verification failed.

原因:目标主机的公钥已经改变,为了防御中间人攻击,需要终止链接。具体动机可百度。

解决方案:

  1. 在服务器和本地端重新配置公私钥

  2. 本地:sudo chmod 600 私钥文件地址

    Permissions 0644 for '/Users/XXX/.ssh/XXX.pem' are too open
  3. ssh-keygen -R 目标访问ip地址(这个操作会删除.ssh/known_hosts中记录的近期公钥
    https://www.ruanyifeng.com/blog/2011/12/ssh_remote_login.html)

  4. 重启服务器

  5. 本地端访问服务器

sudo: unable to resolve host +乱码

sudo: unable to resolve host iZ2ze73nro8igc5iw6qmkgZ
原因:http://code.sike.wang/code/show-5188.html
解决方案:在 etc/hosts 第一行 localhost 后添加这串乱码,这是阿里云创建给的默认主机名

共享协议

本文由 ArrogantL 整理并在 CC BY-NC-SA 3.0 协议下发布。有任何问题请邮件联系 [email protected]

请各位遵循 Markdown: License 及其它参考文献的共享协议来使用、修改和发布。

猜你喜欢

转载自www.cnblogs.com/gjl-blog/p/12305234.html
今日推荐