nginx 负载均衡
2016-07-25
传递 http 请求到后端 http 服务器
这是通过 ngx_http_upstream_module 实现的,例如下面的配置
upstream backend {
server 172.16.0.16:8080 weight=1 max_fails=2 fail_timeout=10s;
server 172.16.0.16:8081 weight=1 max_fails=2 fail_timeout=10s;
server 172.16.0.17:8080 weight=1 max_fails=2 fail_timeout=10s;
server 172.16.0.17:8081 down;
}
server {
location / {
# 传递 http 请求到 backend 服务器
proxy_pass http://backend;
}
# 传递 远程的主机地址
proxy_set_header Host $http_host;
proxy_set_header Forwarded $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
}
server 指令常用的参数如下
- weight: 访问权重,默认值为1
- max_fails: 允许请求失败的次数,默认为1
- fail_timeout: 默认是10s, 有两层含义
- 在 10s 时间内最多容许 2 次失败
- 2次失败以后,10s时间内不分配请求到这台服务器
- backup: 备用服务器, 当其他所有的非 backup 服务器出现故障时,请求backup机器
- max_conns: 同时连接到一台后端服务器的连接数,默认为0即无限制
- down:标识服务器不可用
通过传递 fastcgi 请求到后端 fastcgi 服务器
这是通过 ngx_http_fastcgi_module 实现的,例如下面的配置
upstream fastcgi_backend {
server 172.16.0.16:8080 weight=1 max_fails=2 fail_timeout=10s;
server 172.16.0.17:8080 weight=1 max_fails=2 fail_timeout=10s;
}
server {
listen 8100;
server_name localhost;
index index.html;
location / {
# 传递 fastcgi 请求到 backend 服务器
fastcgi_pass fastcgi_backend;
include fastcgi_params.default;
}
}
nginx 通过 uwsgi 分发请求到 django
这是通过 ngx_http_uwsgi_module 实现的,
nginx 的配置
upstream uwsgi_backend {
server 127.0.0.1:8180 weight=1 max_fails=2 fail_timeout=10s;
}
server {
listen 8100;
server_name localhost;
index index.html;
location / {
# 传递 uwsgi 请求到 backend 服务器
uwsgi_pass uwsgi_backend;
include uwsgi_params.default;
}
}
创建 django 项目
django-admin startproject HelloWorld
添加 HelloWorld/HelloWorld/view.py 文件
#!/usr/bin/env python
# coding: utf-8
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world ! ")
修改 HelloWorld/HelloWorld/urls.py 文件
from django.conf.urls import *
from HelloWorld.view import hello
urlpatterns = patterns("",
('^hello/$', hello),
)
创建 uwsgi 配置文件 uwsgi.ini
注意:chdir 修改成项目的根目录
[uwsgi]
chdir=/data/work/project/HelloWorld
module=HelloWorld.wsgi:application
socket=0.0.0.0:8180
processes=5
master=True
pidfile=/tmp/project-master.pid
vacuum=True
max-requests=5000
daemonize=/var/log/uwsgi_hello.log
启动 uwsgi 服务
uwsgi --ini uwsgi.ini
访问 http://127.0.0.1:8100/hello