天天看点

基于Nginx 和 uwsgi 搭建 Django部署上线环境

环境:阿里云 ECS CentOS 7.2 64位

安装:

  • python3
  • python虚拟环境
  • django
  • uwsgi
  • nginx

安装Python3

不动现有的Python2环境安装Python3

下载Python3

wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tgz

解压Python3

tar -zxvf Python-3.6.1.tgz

进入目录

cd Python-3.6.1

安装到指定目录(本次指定路径

/usr/local/python3

新建文件夹

mkdir -p /usr/local/python3

配置安装路径

./configure --prefix=/usr/local/python3

编译

make

安装

make install

环境配置,让python3命令即输即用

建立python3的软链

ln -s /usr/local/python3/bin/python3 /usr/bin/python3

并将

/usr/local/python3/bin

加入

PATH

:

vim ~/.bash_profile

修改完毕,执行命令,让修改生效:

source ~/.bash_profile

检查Python3是否安装成功:

python3 -V

安装Python3虚拟环境

为啥要安装虚拟环境:

在一个 Python 环境下开发时间越久、安装依赖越多,就越容易出现依赖包冲突的问题。为了解决这个问题,开发者们开发出了 virtualenv,可以搭建虚拟且独立的 Python 环境。这样就可以使每个项目环境与其他项目独立开来,保持环境的干净,解决包冲突问题。

安装 virtualenv,执行命令即可:

pip3 install virtualenv

创建项目的虚拟环境:

virtualenv venv(虚拟环境名称)

执行后,在本地会生成一个与虚拟环境同名的文件夹,包含 Python 可执行文件和 pip 库的拷贝,可用于安装其他包。默认情况下,虚拟环境中不会包含也无法使用系统环境的global site-packages。比如系统环境里安装了 requests 模块,在虚拟环境里import requests会提示ImportError。如果想使用系统环境的第三方软件包,可以在创建虚拟环境时使用参数

–system-site-packages

可以自己指定虚拟环境所使用的 Python 版本,前提系统中已经安装了该版本:

virtualenv -p /usr/bin/python2.7 venv

使用虚拟环境

进入虚拟环境目录,启动虚拟环境。

source venv/bin/activate

看到

(venv)

表示已经进入虚拟环境。

退出虚拟环境:

deactivate

如果项目开发完成后想删除虚拟环境,直接删除虚拟环境目录即可。

安装Django

在虚拟环境中执行命令即可:

pip install django

本次重点介绍Django如何上线部署,Django相关知识不做具体介绍。

新建Django项目:

django-admin startproject 项目名

安装uwsgi

pip install uwsgi

现在重点来啦,上面那么多都只是基本的环境配置。下面的是知识点,部分也是难点,笔者在这个地方被困了很久,所以一定要弄得时候写个博文记录下来。

配置uwsgi

当前目录下创建test.py文件

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return "Hello World" #国际惯例,helloworld           

运行代码:

uwsgi --http :9111 --wsgi-file test.py

报错:

-bash: uwsgi: command not found

遇到这个情况怎么办?肯定不能放弃,干就行啦。

通过pip安装的组件,执行命令文件在python源目录下的bin目录中,所以解决方案:

执行命令:

ln -s /your-python-dir/bin/* /usr/bin/*

*代表你你需要添加的执行命令uwsgi,故障排除,然后继续执行:

uwsgi --http 0:8000 --wsgi-file test.py

成功后提示:

*** Starting uWSGI 2.0.17.1 (64bit) on [Fri Nov 23 12:12:30 2018] ***
compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-28) on 22 November 2018 09:21:34
os: Linux-3.10.0-514.26.2.el7.x86_64 #1 SMP Tue Jul 4 15:04:05 UTC 2017
nodename: iZhp31ku43vn2fbp1dk355Z
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /home/ruanfumin
detected binary path: /usr/local/python3/bin/uwsgi
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 1880
your memory page size is 4096 bytes
detected max file descriptor number: 65535
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uWSGI http bound on 0:8000 fd 4
spawned uWSGI http 1 (pid: 11058)
uwsgi socket 0 bound to TCP address 127.0.0.1:34451 (port auto-assigned) fd 3
Python version: 3.6.1 (default, Nov 22 2018, 17:05:27)  [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0xaa2120
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 72920 bytes (71 KB) for 1 cores
*** Operational MODE: single process ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0xaa2120 pid: 11057 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 11057, cores: 1)           

访问一下IP地址,本机就是

127.0.0.1:8000

,服务器就是

服务器ip:8000

浏览器看到:

Hello World

终端会提示:

[pid: 11057|app: 0|req: 1/1] 183.206.12.47 () {42 vars in 829 bytes} [Fri Nov 23 12:13:17 2018] GET / => generated 11 bytes in 0 msecs (HTTP/1.1 200) 1 headers in 44 bytes (1 switches on core 0)           

表明uwsgi配置ok,咱继续

直接使用Django跑一下项目,看能不能运行成功,由于Django是在阿里云服务器上,所以项目设置文件settings.py需要修改一下。

ALLOWED_HOSTS = ['*']           

酱紫就可以访问了。咱跑一下试试:

python manage.py runserver 0:8000

使用Uwsgi 跑 django项目

在项目(新建的测试项目

testproject

)路径下,执行:

uwsgi --http 0:8000 --module testproject.wsgi

解释:

--http 0:8000

携带这个参数表明可以http访问,端口号是8000。

--module testproject.wsgi

指定Django项目的wsgi文件。

参考Django官方文档:

uwsgi --chdir=/path/to/your/project \
    --module=mysite.wsgi:application \
    --env DJANGO_SETTINGS_MODULE=mysite.settings \
    --master --pidfile=/tmp/project-master.pid \
    --socket=127.0.0.1:49152 \      # can also be a file
    --processes=5 \                 # number of worker processes
    --uid=1000 --gid=2000 \         # if root, uwsgi can drop privileges
    --harakiri=20 \                 # respawn processes taking more than 20 seconds
    --max-requests=5000 \           # respawn processes after serving 5000 requests
    --vacuum \                      # clear environment on exit
    --home=/path/to/virtual/env \   # optional path to a virtualenv
    --daemonize=/var/log/uwsgi/yourproject.log      # background the process           

再次访问:

http://39.104.91.28:8000/

发现还是成功辣,真好。

在项目目录下新建

uwsgi.ini

文件,可以参考

官方文档
[uwsgi]
#chidr用于指定自己的网站根目录(自行更改)
chdir =  /var/www/testproject
#module指定网站中APP的文件(自行更改)
module = testproject.wsgi
#home用于指定python的虚拟环境,即我们最初创建的虚拟环境位置(自行更改)
home = /var/www/venv
#master不用更改
master = true
#socket用于指定端口号,可以不更改
socket = :8000
#以下两个可以不用更改
chmod-socket = 666           

文件里我们指定socket,让Nginx服务器通过这个socket处理uwsgi。

Nginx安装:

这个不细说了,直接yum命令就好:

yum install nginx

Nginx配置修改

进入Nginx配置目录,在

/etc/nginx/

下:

我们修改

nginx.conf

文件:

upstream django_test { #加上_test,因为和原来的冲突了,这里备注下
    # server unix:///path/to/your/mysite/mysite.sock; # for a file socket
    server 127.0.0.1:8000; # for a web port socket (we'll use this first) 类似uwsgi端口
}

    server {
        listen       80;
        server_name  ruanfumin;


        location / {
            include uwsgi_params;
            uwsgi_pass django_test;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
        location /static {
        alias /var/www/first/static; # 加载你的静态文件
    }

    }
           

修改完,保存,重启Nginx服务器,然后再到Django项目目录下启动uwsgi服务:

uwsgi --ini uwsgi.ini

浏览器输入url访问:

39.104.91.28:80

当然这次是80端口访问了,因为Nginx我们设置的嘛,你可以随意修改。

注: