nginx+web.py+python+uwsgi负载均衡

材料:
1、nginx(最新版)
2、web.py(最新版)
3、python(2.7版本)
4、uwsgi(最新版)
5、ubuntu系统服务器两台(192.168.0.221、192.168.1.22)
6、网络环境:局域网

第一步、安装nginx

apt-get install nginx

第二步、安装uwsgi:

下载地址 https://pypi.org/project/uWSGI/#files
下载后得到文件uwsgi-2.0.17.1.tar.gz 
解压后进入uwsgi-2.0.17.1文件夹
执行python setup.py install 命令,静静等待安装完毕即可。

第三步、安装web.py

使用pip安装既方便又快捷:  pip install web.py
(我第一次用的是python3.4,安装web.py出现各种奇葩错误,网上有人说是web.py不支持高版本的python,遂改为python2.7,结果安装很顺利)

第四步、修改nginx配置文件

/etc/nginx/conf.d/default.conf

 1upstream backend{
 2        #ip_hash;
 3        server 192.168.1.22:1234 max_fails=5 fail_timeout=60s;  #负载均衡服务器群
 4        server 192.168.0.221:1234 max_fails=5 fail_timeout=60s;
 5        keepalive 64;
 6}
 7
 8server {
 9    listen       8002;
10    server_name  cunhua;
11    error_log /etc/nginx/logs/test.log;
12
13    location / {
14        root   html;
15        #uwsgi_pass 192.168.1.22:1234;
16        uwsgi_pass backend;
17        include uwsgi_params;
18        index  index.html index.htm;
19    }
20    error_page  404              /404.html;
21
22    error_page   500 502 503 504  /50x.html;
23    location = /50x.html {
24        root   /usr/share/nginx/html;
25    }
26}

第五步、项目文件

code.py文件

 1import web
 2render = web.template.render('templates/')
 3
 4urls = (
 5    '/', 'index'
 6)
 7
 8app = web.application(urls, globals())
 9
10
11class index:
12    def GET(self):
13      name = 'Bob'
14      return render.index()
15
16
17application = app.wsgifunc()
18
19
20if __name__ == "__main__":
21    app = web.application(urls, globals())
22    app.run()

index.html文件内容:
<em>Hello</em>, 我是翠花!

项目目录截图如下:

因为是要做负载均衡所以需要把代码分别部署到192.168.0.221192.168.1.22两台服务器上。
为了区分负载均衡的效果,我们把221上的index.html内容改为:

Hello, 我是翠花!

把22服务器上的index.html内容改为:

Hello, 俺是秋香!

项目代码位置统一都是

/home/liushisan/MyGames

第六步、用uwsgi加载项目

分别进入两台服务器的代码目录

cd /home/liushisan/MyGames
随后执行  uwsgi -s 0.0.0.0:1234 -w code

此时访问 http://192.168.1.22:8002/
页面输出:

Hello, 我是翠花!

再次刷新页面后页面输出:

Hello, 俺是秋香

至此,完成负载均衡的全部配置。

欢迎大家关注我的微信公众号:

猜你喜欢

转载自blog.csdn.net/javahuazaili/article/details/81490624