安装uwsgi
环境是ubuntu18.04+python3.8.8
首先安装好anaconda环境,后面的包都用conda安装,能自动解决依赖问题。
- conda换清华源
conda config --add channels conda-forge
conda config --set channel_priority flexible
conda update -n base conda
conda update --all
conda install -c conda-forge uwsgi
验证uwsgi安装成功
新建文件test.py
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World"]
输入命令
uwsgi --http :8001 --wsgi-file test.py
安装nginx
sudo apt-get install nginx
验证nginx安装成功
改nginx.conf(改之前先备份)
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
server {
listen 8080;
server_name localhost;
charset utf-8;
location / {
root html;
index index.html inde.htm;
}
}
}
root账号运行命令
sudo su
nginx
配置nginx+uwsgi+django
先说明django的目录,根目录为./demo_web
django的特殊目录结构,根目录 demo_web
内包含了一个django的工作文件夹demo_web
,此外还包含网页模板文件夹templates
和静态资源文件夹(图片)media
,还包含一些其他的配置文件。
uwsgi
首先,我们要在根目录下创建一个uwsgi配置文件,以代替上面用命令行启动uwsgi的方式,新建一个demo_web_uwsgi.ini
文件,将以下内容写入
[uwsgi]
# for web 当使用uwsgi作为单一服务器时用这个
# http = 0.0.0.0:8080
# for nginx 当配合nginx使用时用这个,uwsgi和nginx是通过socket通信的
socket = :8081
# the base directory (full path) 根目录
chdir = /home/ubuntu/workspaces/demo_web
# Django wsgi file 以python包的格式导入
module = demo_web.wsgi
# process-related settings
# master
master = true
# maximum number of worker processes
processes = 4
buffer-size = 65536
# ... with appropriate permissions - may be needed
chmod-socket = 664
# clear environment on exit
vacuum = true
启动uwsgi:
uwsgi --ini uwsgi.ini # 正常启动
uwsgi -d --ini uwsgi.ini # 后台启动
nginx
nginx 配置的文件在/etc/nginx/nginx.conf
,修改前先备份到nginx.conf.bak
中,将以下内容写入nginx.conf
中:
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
server {
listen 8080; # 客户端接入端口
server_name localhost;
charset utf-8;
access_log /var/log/nginx/myweb_access.log; # nginx正常的访问日志
error_log /var/log/nginx/myweb_error.log; # nginx的错误日志
location / { # 这两句很关键,实现nginx和uwsgi绑定
include uwsgi_params;
uwsgi_pass 127.0.0.1:8081; # 这里的端口和uwsgi里面的配置应该一致
}
location /media/ {
alias /home/ubuntu/workspaces/demo_web/media/; # 静态资源路径和文件目录都要和django里面的名称一致
}
}
}
启动nginx
# 启动nginx
nginx
# 停止nginx
nginx -s stop
# 重启nginx
nginx -s reload
# 后台启动可以用nohup
启动nginx后就可以正常访问8080端口了。