Ubuntu下配置nginx+uwsgi+django

安装uwsgi

环境是ubuntu18.04+python3.8.8
首先安装好anaconda环境,后面的包都用conda安装,能自动解决依赖问题。

  1. conda换清华源
  2. conda config --add channels conda-forge
  3. conda config --set channel_priority flexible
  4. conda update -n base conda
  5. conda update --all
  6. 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

  1. 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端口了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值