首页 > 系统相关 >Django+nginx+uwsgi

Django+nginx+uwsgi

时间:2024-02-13 19:34:55浏览次数:48  
标签:grep server nginx html conf Django uwsgi

在云服务器上搭建web网站
服务器的系统是CentOS 7.6

一、安装Python 3.8.18

1、 安装gcc

yum install gcc -y

2、 安装编译python的依赖

yum install zlib zlib-devel -y
yum install bzip2 bzip2-devel -y
yum install ncurses ncurses-devel -y
yum install readline readline-devel -y
yum install openssl openssl-devel -y
yum install sqlite sqlite-devel -y
yum install tk tk-devel -y
yum install libffi-devel -y
yum install gdbm gdbm-devel -y
yum install xz lzma xz-devel -y
yum install mysql-devel -y
yum install python-devel -y

3、下载python3.8.18源码

cd /data/
wget https://www.python.org/ftp/pyhon/版本号/Python-版本号.tgz

4、解压 编译 安装

tar -xvf Python-3.8.18.tgz
cd python-3.8.18
./configure    (./configure --prefix=/usr/local/python3   第一个指定安装的路径,不指定的话,安装过程中可能软件所需要的文件复制到其他不同目录,删除软件很不方便,复制软件也不方便.)
make all
make install


# 添加python3的软链接 
ln -s /usr/local/python3/bin/python3.8 /usr/bin/python3 
 
# 添加 pip3 的软链接 
ln -s /usr/local/python3/bin/pip3.8 /usr/bin/pip3

ls -ls
ll
都是查看软连接指向的命令

二、Python虚拟环境

1、安装virtualenv

pip3 install virtualenv

2、创建虚拟环境

(mainWeb(用项目名创建虚拟环境,这样,一个虚拟环境对应的项目))

mkdir /envs  创建/envs目录,用于创建虚拟环境
virtualenv /envs/mainWeb --python=python3.8   创建虚拟环境mainWeb,并指定python版本

当virtualenv的程序文件没有在环境变量配置的路径上时,以上命令会报错,需要找到virtualenv程序文件所在目录,将它添加到环境变量中(通过修改/etc/profile或用户目录的.bashrc)

另外,/envs目录 用户没有修改权限也会报错,需sudo chmod 777 /envs

3、激活虚拟环境

source /envs/mainWeb/bin/activate

4、运行项目

source /envs/mainWeb/bin/activate
cd /data/www/mainWeb
python manage.py runserver

这样可以把项目运行起来

但一般不这样做。

三、uwsgi

a、安装

source /envs/mainWeb/bin/activate
pip3 install uwsgi

b、基于uwsgi运行项目

命令的方式
uwsgi --http:8080 --wsgi-file app.py --callable app (运行flask项目的命令)
运行mainWeb项目:
uwsgi --http 0.0.0.0:80 --file mainWeb/wsgi.py --static-map=/static=statics
配置文件(推荐)
创建文件:nb_uwsgi.ini (文件名任意.ini)
运行mainWeb项目:

[uwsgi]
http = 0.0.0.0:8000
chdir=/data/www/main-web
module=mainWeb.wsgi
wsgi-file=mainWeb/wsgi.py
master = true
processes=2
threads=2
#uid=1000
#gid=1000
max-requests=2000
vacuum=true
#daemonize=/data/wwww/main-web/uwsgi.log
enable-threads = true

执行命令:

source /envs/nb/bin/activate
uwsgi  --ini  nb_uwsgi.ini 

以后台的模式运行(加符号&): uwsgi --ini nb_uwsgi.ini &
停止uwsgi:

ps -ef|grep nb_uwsgi  找到进程的编号
kill -9 进程编号

四、Nginx

利用Nginx做反向代理和处理静态文件

a、安装

yum install nginx -y

b、配置

以下是wupeiqi老师的教程。但https://www.cnblogs.com/suguangti/p/11334692.html这个做法更好,不用修改默认的conf文件(https://www.cnblogs.com/makerchen/p/15364448.html)。

    在自己的工程目录下,建立如destiny.conf(/wwwroot/destiny/destiny.conf)的配置文件;复制nginx.conf里面全部的内容,全部写入destiny.conf中。
    然后按照下面写的,把destiny.conf配置文件中的server段部分全部替换掉。

● 普通请求 -> 8001端口
● /static/ -> /data/www/day28/static
修改nginx.conf配置文件: /etc/nginx/nginx.conf
/etc/nginx/nginx.conf 原始内容:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

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

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2;
#        listen       [::]:443 ssl http2;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}

flask项目的nginx.conf:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    upstream flask {
      server  127.0.0.1:8001;
    }

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location /static {
          alias /data/www/day28/static;
        }
        location / {
          uwsgi_pass  flask;
          include     uwsgi_params;
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2;
#        listen       [::]:443 ssl http2;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}

nginx的默认配置文件路径 /etc/nginx/nginx.conf

2.1 删除默认的nginx.conf

rm nginx.conf

2.2 新建nginx.conf + 内容拷贝 + 保存

cd /etc/nginx/
vim nginx.conf 创建并打开文件
... (编辑内容然后保存退出)

cat 文件 查看文件

c、启动nginx

● 启动
○ systemctl start nginx
○ systemctl stop nginx
○ systemctl restart nginx
● 开机启动
○ systemctl enable nginx

d、访问

五、shell脚本启动、停止uwsgi

a、重启

reboot.sh

#!/usr/bin/env bash

echo -e "\033[34m------------wsgi process------------\033[0m"

ps -ef|grep nb_uwsgi.ini | grep -v grep

sleep 0.5

echo -e '\n--------------going to close--------------'

ps -ef |grep nb_uwsgi.ini | grep -v grep | awk '{print $2}' | xargs kill -9

sleep 0.5

echo -e '\n----------check if the kill action is correct------------'

/envs/nb/bin/uwsgi --ini  nb_uwsgi.ini & >/dev/null

echo -e '\n\033[42;1m-----------------started...----------------------\033[0m'
sleep 1

ps -ef |grep nb_uwsgi.ini | grep -v grep

b、停止

stop.sh

#!/usr/bin/env bash

echo -e "\033[34m------------wsgi process------------\033[0m"

ps -ef|grep nb_uwsgi.ini | grep -v grep

sleep 0.5

echo -e '\n--------------going to close--------------'

ps -ef |grep nb_uwsgi.ini | grep -v grep | awk '{print $2}' | xargs kill -9

sleep 0.5

这些文件放在git仓库,通过git同步到服务器

给脚本文件赋予可执行权限:
chmod 755 reboot.sh
chmod 755 stop.sh

./reboot.sh 即可运行脚本

六、实践中

mw_uwsgi.ini

[uwsgi]
uid = 1000   #普通用户运行 注释实际去掉
gid = 1000
socket = 127.0.0.1:9090
chdir = /data/www/main-web
wsgi-file = mainWeb/wsgi.py
processes = 1
threads = 1
master = true
module = mainWeb.wsgi
chmod-socket=664
enable-threads = true
virtualenv = /envs/mainWeb/
max-requests = 2000
daemonize = /data/www/main-web/uwsgi.log    #加了这句。uwsgi --ini ....启动uwsgi,则自动在后台运行。这个注释实际项目也应该删掉

mainWeb.conf

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  localhost;
        root         /usr/share/nginx/html;


        charset     utf-8;
        access_log      /data/www/main-web/nginx_access.log;
        error_log       /data/www/main-web/nginx_error.log;
        client_max_body_size 75M;


         location /static {
             alias /data/www/main-web/statics;
         }

         location / {
             include     /etc/nginx/uwsgi_params;
             uwsgi_pass  127.0.0.1:9090;
         }

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

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

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2;
#        listen       [::]:443 ssl http2;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}

服务器运行命令:

nginx -c /data/www/main-web/mainWeb.conf      #这里的-c 表示加载配置文件启动
nginx -s reload
uwsgi --ini mw_uwsgi.ini 

reboot.sh

#!/usr/bin/env bash

echo -e "\033[34m------------wsgi process------------\033[0m"

ps -ef|grep mw_uwsgi.ini | grep -v grep

sleep 0.5

echo -e '\n--------------going to close--------------'

ps -ef |grep mw_uwsgi.ini | grep -v grep | awk '{print $2}' | xargs kill -9

sleep 0.5

echo -e '\n----------check if the kill action is correct------------'

/envs/mainWeb/bin/uwsgi --ini  mw_uwsgi.ini & >/dev/null

echo -e '\n\033[42;1m-----------------started...----------------------\033[0m'
sleep 1

ps -ef |grep mw_uwsgi.ini | grep -v grep

stop.sh

#!/usr/bin/env bash

echo -e "\033[34m------------wsgi process------------\033[0m"

ps -ef|grep mw_uwsgi.ini | grep -v grep

sleep 0.5

echo -e '\n--------------going to close--------------'

ps -ef |grep mw_uwsgi.ini | grep -v grep | awk '{print $2}' | xargs kill -9

sleep 0.5

标签:grep,server,nginx,html,conf,Django,uwsgi
From: https://www.cnblogs.com/zhlforhe/p/18014763

相关文章

  • Django 模版变量
    Django模版变量Django模版语言的语法主要分为以下四个部分:变量标签过滤器注释一、模版变量1)变量的命名规范Django对于模版变量的命名规范没有太多的要求,可以使用任何字母、数字和下划线的组合来命名,且必须以字母或下划线开头,但是变量名称中不能有空格或者标点符号。2......
  • 三十五、Django实践的笔记
    Django时间时区datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S'),得到的是标准时区的时间字符串https://blog.csdn.net/qiaominghe/article/details/86593744https://blog.csdn.net/qq_42778001/article/details/111088130https://zhuanlan.zhihu.com/p/24246164fro......
  • python3.9 + django4.1 + vue3 ,报错,无法访问配置的路由地址,Using the URLconf defined
    python3.9+django4.1+vue3,报错,无法访问配置的路由地址,UsingtheURLconfdefinedinStudentMgrBE.urls,DjangotriedtheseURLpatterns,inthisorder:-------------------------------------------------------------------------------无法访问 地址,报错如下: Us......
  • 二十三、Django之Form组件
    Django的Form:1、对用户请求的验证2、生成HTML代码a、创建一个类b、类中创建字段(包含正则表达式)c、Geta)Obj=Fr()obj.user=>自动生成HTMLd、POSTa)Obj=Fr(request,POST)i.Ifobj.is_valid():Obj.cleaned_dataElse:......
  • 二十四、Django Serializes
    SerializersDjango中,自定义类型的对象无法通过json序列化,可以使用serializers。defget_data(request):#由于UserInfo是自定义对象,不能通过json序列化#因此使用以下方式fromdjango.coreimportserializersret={'status':True,'data':None}try:......
  • nginx容器配置方案
    nginx容器配置可以参考docker官网nginx页面的默认配置docker-nginx官网howtouseimage这里面提供了一些demo,可以帮助我们快速的启动nginx容器,并且除了常规的挂载、端口等基本配置外,还提供了以只读方式启动、以debug模式启动、设置日志等级环境变量等演示。下文仅是博主根据......
  • 十八、Django之Http
    1、Django请求的生命周期请求响应Http1、发送Http请求请求头(包含Cookie)\r\n\r\n请求体2、服务器请求,根据请求头中的url在路由关系表中进行匹配(从上到下)3、匹配成功后,执行指定的views函数a.Url->函数==>FBVb.Url->类==>CBV4、响应内......
  • 十六、Django的ORM(二)
    1、DecimalFieldDecimalField保存浮点型数据比FloatField精确,因为它是以字符串来保存,而FloatField,数据越长,保存得越不精确。2、索引(命中索引)正确使用SQL语言,使查找数据时,用到索引username=models.CharField(...#db_index=True数据库中字段是否可以建立......
  • 十五、Django的ORM
    单表操作1、表记录的添加方式一:Book()+obj.save()b=Book(name="python基础",price=99,author="yuan",pub_date="2017-12-12")b.save()#将b存到数据库方式二:createBook.objects.create(name="linux",price=78,author="HK",pub_date="......
  • 十四、MySQL与Django之Model基础
    数据库Django默认支持sqlite、mysql、oracel、postgresql等数据库1、sqlitedjango默认使用sqlite数据库Django.db.backends.sqlite3DATABASES={'default':{'ENGINE':'django.db.backends.sqlite3','NAME':os.path.join(BA......