您的位置:首页 > 运维架构 > 反向代理

Nginx反向代理,健康状态检测,过载保护及配置文件详解

2013-09-15 20:19 681 查看
简介

Nginx("engine x")是一个高性能的HTTP和反向代理 服务器,也是一个IMAP/POP3/SMTP 代理服务器。Nginx 是由Igor Sysoev为俄罗斯访问量第二的Rambler.ru站点开发的,第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、占有内存少,并发能力强、丰富的功能集、示例配置文件和低系统资源的消耗而闻名

一、Nginx的主配置文件详解(nginx.conf)
user nobody nobody; #运行用户与组
worker_processes 6; #启动进程,通常设置与CPU数相同
worder_cpu_affinity 4; #明确指定使用哪些CPU 如使用1、3核心: 1000 0010
worker_rlimit_nofile 51200; #设置最大系统连接数
worker_priority 1; #指定调用CPU优先级;取值范围(-20~20)
#error_log logs/error.log;
#error_log logs/error.log notice; #错误日志及日志级别;日志级别有:(debug|info|notice|warn|error|crit|alert|emerg)
#error_log logs/error.log info;
#pid logs/nginx.pid; #PID文件路径
lock_file logs/nginx.lock; #锁文件路径
events { #事件模块
use epoll; #指定事件驱动模型;(kqueue|rtsig|epoll|select|poll|eventport)
worker_connections 51200; #定义连接数限制;当超过1024时,须使用"ulimit -n"来解除系统连接限制
}
http { #设置HTTP服务器模块
include mime.types; #设置MIME类型
default_type application/octet-stream; #默认文件系统
#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 logs/access.log main; #设置访问日志及日志格式
sendfile on; #指定Nginx是否调用sedfile函数
#autoindex on; #开启索引功能,适合下载服务器,默认关闭

#tcp_nopush on; #防止网络阻塞
#tcp_nodelay on; #防止网络阻塞
#keepalive_timeout 0;
keepalive_timeout 65; #连接超时时间,单位秒
server_names_hash_bucket_size 128; #服务器名字Hash表大小
large_client_header_buffers 4 32k; #设定请求缓存大小
client_header_buffer_size 2k; #客户端请求头部缓冲区大小
client_body_buffer_size 512k; #客户端请求主休缓冲区大小
client_header_timeout 60; #客户端请求头部超时时间
client_max_body_size 8M; #设置通过Nginx上传的文件大小
proxy_connect_timeout 20; #代理连接超时时间
proxy_send_timeout 60; #代理发送超时时间
proxy_read_timeout 20; #代理接收超时时间
proxy_buffer_size 16k; #代理服务器保存用户头信息的缓冲区大小
proxy_buffers 4 64k; #存放后台服务器缓冲区数量与大小
proxy_busy_buffers_size 128k; #高负荷下缓冲大小
proxy_temp_file_write_size 128k; #设置缓存文件夹大小
proxy_temp_path /usr/cache_one; #设置缓存文件夹位置
######指定缓冲区的路径、存储方式及大小

proxy_cache_path /usr/proxy_cache_path levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;
gzip on; #开启Gzip压缩功能
gzip_min_length 1k; #最小压缩文件大小
gzip_buffers 4 16k; #压缩缓存区
gzip_http_version 1.1; #压缩版本
gzip_proxied off; #在代理中是否启用压缩功能
gzip_comp_level 5; #压缩级别;默认为1,取值范围(1-9)
######压缩文件类型

gzip_types text/plain application/x-javascript text/css application/xml application/javascript;
gzip_vary on;
upstream allen { #定义负载均衡配置,必须定义在"server"之外
ip_hash; #基于客户端IP地址完成请求的分发,可以实现同一个客户端的请求发送到同一台服务器;有三种调度算法:轮询(round-robin)、ip哈希(ip_hash)和最少连接(least_conn)
server 172.16.14.2 weight=1;#定义一个后端服务器;weight:权重 max_fails:最大失败连接次数,失败连接超时时间由fail_timeout设置 fail_timeout:等待请求目标服务器发送响应时长 backup:所有服务器都故障时才启用此服务器 down:手动记录此服务器不在做任何处理请求
server 172.16.14.3 weight=1;
}
server { #定义一个虚拟主机,可以定义多个
listen 80; #监听端口
server_name www.allen.com; #定义主机名称
#charset koi8-r; #设置字符集
#access_log logs/host.access.log main;
location / { #可以定义多个,也可以嵌套
root /web; #设置网站文件存放目录
index index.php index.html index.htm; #设置默认访问主页
}
location /status {
stub_status on; #开启Nginx状态监测
access_log off; #关闭日志访问
}
location ~ \.php$ { #定义以".php"结尾的文件
root /web; #定义php服务器网站存放目录
fastcgi_pass 172.16.14.2:9000; #定义fastcgi服务器地址及端口
fastcgi_index index.php; #定义默认访问主页
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params; #定义fastcgi访问文件
}
#location ~ .*\.(gif|jep|jpeg|png|bmp|swf|js|css|js|)$ {
# proxy_cache cache_one; #设置缓存区
# proxy_cache_valid 200 304 12h; #设置缓存时间
# proxy_cache_valid 301 302 1m;
# proxy_cache_valid any 1m;
# proxy_set_header Host $host; #设置发送到代理服务器请求头部添加额外信息
# proxy_set_header X-Real-IP $remote_addr;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_pass http://allen; #}
#location / {
# if ($request_method == “PUT”) { #如果客户请求动作为"PUT"就转到定义的地址
# proxy_pass http://www.allen.com:8080;
# }

# if ($request_uri ~ "\.(jpg|gif|jpeg|png)$") { #如果客户端请求"uri"有已经定义的文件结尾的文件就转到定义好的地址然后跳出
# proxy_pass http://imageservers; # break;
# }
#if ($http_user_agent ~ MSIE) { #如果客户端请求使用的浏览器是IE,不管请求地址是什么都转到"/msie/"下面并跳出
#rewrite ^(.*)$ /msie/$1 break;
注释:
·last - 完成重写指令,之后搜索相应的URI或location。
·break - 完成重写指令。
·redirect - 返回302临时重定向,如果替换字段用http://开头则被使用。
·permanent - 返回301永久重定向
#}
#}
#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html; #定义错误返回页面
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1; #定义以".php"结尾的全部转到指定的地址
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration

#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server { #定义一个HTTPS服务器
# listen 443;
# server_name localhost;
# ssl on;
# ssl_certificate cert.pem; #私钥文件
# ssl_certificate_key cert.key; #颁发的证书
# ssl_session_timeout 5m; #会话超时时间
# ssl_protocols SSLv2 SSLv3 TLSv1; #SSL协议版本
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
if语句
语法:if (condition) { ... }
默认值:none
使用字段:server, location
判断一个条件,如果条件成立,则后面的大括号内的语句将执行,相关配置从上级继承。
可以在判断语句中指定下列值:
·一个变量的名称;不成立的值为:空字符传""或者一些用“0”开始的字符串。
·一个使用=或者!=运算符的比较语句。
·使用符号~*和~模式匹配的正则表达式:
URL重写模块(Rewrite)
·~为区分大小写的匹配。
·~*不区分大小写的匹配(allen匹配Allen)。
·!~和!~*意为“不匹配的”。
·使用-f和!-f检查一个文件是否存在。
·使用-d和!-d检查一个目录是否存在。
·使用-e和!-e检查一个文件,目录或者软链接是否存在。
·使用-x和!-x检查一个文件是否为可执行文件。
正则表达式的一部分可以用圆括号,方便之后按照顺序用$1-$9来引用。
示例配置:
if ($http_cookie ~* "id=([^;] +)(?:;|$)" ) {
set $id $1;
}
if ($request_method = POST ) {
return 405;
}
if (!-f $request_filename) {
break;
proxy_pass http://127.0.0.1; }
if ($slow) {
limit_rate 10k;
}
if ($invalid_referer) {
return 403;
}
if ($args ^~ post=140){
rewrite ^ http://example.com/ permanent;
}
<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
Nginx负载均衡配置
下面使用一个案例来介绍Nginx如何配置负载均衡:



注释: 这里为方便做实验就使用一个网段
Nginx服务器做负载均衡调度器,这个拓扑图中只做了一台调度器,也就是单点故障,这样会成会整个系统的瓶颈,这里就不做高可用了,当然后续会介绍高可用的实现
两台WEB服务器就使用"Apahce"来实现,这里使用rpm包安装方式;然后提供一个测试页面
1、编译安装Nginx
######安装Nginx依赖环境
[root@nginx ~]# yum -y groupinstall "Development tools" "Server Platform Development"
[root@nginx ~]# yum -y install pcre-devel
=====================================================
######添加Nginx运行用户
[root@nginx ~]# useradd -r nginx
[root@nginx ~]# tar xf nginx-1.4.2.tar.gz
[root@nginx ~]# cd nginx-1.4.2
######编译安装Nginx
[root@nginx nginx-1.4.2]# ./configure \
>   --prefix=/usr \                      #Nginx安装目录
>   --sbin-path=/usr/sbin/nginx \        #nginx执行程序安装路径
>   --conf-path=/etc/nginx/nginx.conf \  #Nginx主配置文件存放路径
>   --error-log-path=/var/log/nginx/error.log \   #日志文件存放路径
>   --http-log-path=/var/log/nginx/access.log \
>   --pid-path=/var/run/nginx/nginx.pid  \        #PID文件存放路径
>   --lock-path=/var/lock/nginx.lock \            #锁文件存放路径
>   --user=nginx \                                #指定运行Nginx用户
>   --group=nginx \                               #指定运行Nginx组
>   --with-http_ssl_module \                      #开启SSL加密模块
>   --with-http_flv_module \                      #支持flv流媒体模块
>   --with-http_stub_status_module \              #开启状态检测模块
>   --with-http_gzip_static_module \              #开启gzip静态压缩模块
>   --http-client-body-temp-path=/var/tmp/nginx/client/ \ #客户端请求的缓存目录
>   --http-proxy-temp-path=/var/tmp/nginx/proxy/ \        #代理缓存目录
>   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \       #fcgi缓存目录
>   --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \         #uwsgi缓存目录
>   --http-scgi-temp-path=/var/tmp/nginx/scgi \           #scgi缓存目录
>   --with-pcre                                           #启动正则表达式
[root@nginx nginx-1.4.2]# make && make install
2、为Nginx提供Sysv服务脚本

#!/bin/sh
# nginx - this script starts and stops the nginx daemon
# chkconfig:   - 85 15
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
make_dirs() {
# make required directories
user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
options=`$nginx -V 2>&1 | grep 'configure arguments:'`
for opt in $options; do
if [ `echo $opt | grep '.*-temp-path'` ]; then
value=`echo $opt | cut -d "=" -f 2`
if [ ! -d "$value" ]; then
# echo "creating" $value
mkdir -p $value && chown -R $user $value
fi
fi
done
}
start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
make_dirs
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $prog: "
killproc $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
configtest || return $?
stop
sleep 1
start
}
reload() {
configtest || return $?
echo -n $"Reloading $prog: "
killproc $nginx -HUP
RETVAL=$?
echo
}
force_reload() {
restart
}
configtest() {
$nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart|configtest)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
exit 2
esac
3、将Nginx加入到系统服务并启动
[root@nginx ~]# chmod +x /etc/rc.d/init.d/nginx
[root@nginx ~]# chkconfig --add nginx
[root@nginx ~]# service nginx start
正在启动 nginx:                                           [确定]
4、查看Nginx进程并访问测试

[root@nginx ~]# ps aux|grep nginx
root      2557  0.0  0.2  44444   816 ?        Ss   15:20   0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx     2558  0.7  0.5  44852  1508 ?        S    15:20   0:00 nginx: worker process



5、在WEB1服务器上安装Httpd并启动
[root@web1 ~]# yum -y install httpd
[root@web1 ~]# service httpd start
6、为WEB1服务器提供一个测试页面并做访问测试
[root@web1 ~]# echo 'web1 172.16.14.2' > /var/www/html/index.html



7、在WEB2服务器上面安装Httpd并启动
[root@web2 ~]# yum -y install httpd
[root@web2 ~]# service httpd start
8、为WEB2服务器提供一个测试页面并做访问测试

[root@web2 ~]# echo 'web1 172.16.14.3' > /var/www/html/index.html



配置Nginx实现均衡

1、修改主配置文件
#user  nobody;
worker_processes  4;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
worker_rlimit_nofile    51200;
#pid        logs/nginx.pid;
events {
use epoll;
worker_connections  1024;
}
http {
include       mime.types;
default_type  application/octet-stream;
#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  logs/access.log  main;
server_names_hash_bucket_size 128;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 300m;
client_body_buffer_size 512k;
sendfile        on;
tcp_nopush      on;
keepalive_timeout  65;
proxy_connect_timeout   20;
proxy_send_timeout      60;
proxy_read_timeout      20;
proxy_buffer_size       16k;
proxy_buffers           4 64k;
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 128k;
gzip  on;
gzip_min_length  1k;
gzip_buffers     4 16k;
gzip_http_version 1.1;
gzip_comp_level 5;
gzip_vary on;
upstream allen {
server 172.16.14.2;
server 172.16.14.3;
}
server {
listen       80;
server_name  localhost;
#charset koi8-r;
#access_log  logs/host.access.log  main;
location / {
proxy_pass  http://allen; index  index.html index.htm;
}
# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   html;
}
}
}
2、测试Nginx主配置文件语法,并重新加载
[root@nginx ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@nginx ~]# service nginx reload
3、访问Nginx主机验证是否实现负载均衡,有时可能需要多刷新几下






Nginx实现后端健康状态检测
1、修改Nginx主配置文件如下
upstream allen {
server 172.16.14.2      backup;
server 172.16.14.3      max_fails=3 fail_timeout=2s;
}
注释:
backup:作为备份服务器,当所有服务器都停止了服务,此时backup备份机会启用
max_fails:请求超时后,最大检测后端服务器次数
fail_timeout:超时时间;默认为10s
2、重新加载配置文件
[root@nginx ~]# service nginx reload
3、测试是否访问的页面为WEB2服务器的



4、停止WEB2服务器的Httpd服务,验证是否请求的为WEB1服务器内容

[root@web2 ~]# service httpd stop
Stopping httpd:                                            [  OK  ]



5、把WEB2服务器Httpd服务启动,此时请求到的内容为WEB2服务器;这里就不在测试了

给Nginx添加第三方模块实现过载保护

1、下载扩展补丁包,解压并打补丁 点此下载
[root@nginx ~]# unzip nginx-http-sysguard-master.zip
[root@nginx ~]# cd nginx-1.4.2
[root@nginx nginx-1.4.2]# patch -p1 < ../nginx-http-sysguard-master/nginx_sysguard_1.3.9.patch
2、重新编译安装Nginx
[root@nginx nginx-1.4.2]# ./configure \
>   --prefix=/usr \
>   --sbin-path=/usr/sbin/nginx \
>   --conf-path=/etc/nginx/nginx.conf \
>   --error-log-path=/var/log/nginx/error.log \
>   --http-log-path=/var/log/nginx/access.log \
>   --pid-path=/var/run/nginx/nginx.pid  \
>   --lock-path=/var/lock/nginx.lock \
>   --user=nginx \
>   --group=nginx \
>   --with-http_ssl_module \
>   --with-http_flv_module \
>   --with-http_stub_status_module \
>   --with-http_gzip_static_module \
>   --http-client-body-temp-path=/var/tmp/nginx/client/ \
>   --http-proxy-temp-path=/var/tmp/nginx/proxy/ \
>   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
>   --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \
>   --http-scgi-temp-path=/var/tmp/nginx/scgi \
>   --with-pcre \
>   --add-module=/root/nginx-http-sysguard-master/
[root@nginx nginx-1.4.2]# make && make install
3、修改Nginx配置文件添加过载保护;这里说明下为了测试方便,把CPU负载调的比较低
[root@nginx nginx-1.4.2]# cd /etc/nginx/
[root@nginx nginx]# vim nginx.conf
######在"server"模块中添加如下内容
sysguard on;    #开启过载保护功能
sysguard_load load=0.3 action=/loadlimit;    #cpu负载超过0.3就保护,"action"过载保护动作
#sysguard_mem swapratio=20% action=/swaplimit; #交换分区过载保
#sysguard_mem free=100M action=/freelimit;     #内存过载保护
location /loadlimit {
return 503;    #系统过载返回503
}
注释:由于新添加了功能需要重启Nginx服务
[root@nginx nginx]# service nginx restart
4、安装"htop"工具,监测负载
[root@nginx ~]# yum -y install htop
[root@nginx ~]# htop



5、在另一台主机使用apache自带的压力测试工具ab做压测;在压测前先访问一下是否正常如:



######做压力测试
[root@web1 ~]# ab -n 50000 -c 1000 http://172.16.14.1/index.html[/code]6、查看Nginx服务器的负载状况 


7、测试访问Nginx服务器是否能正常访问



Nginx负载均衡、后端服务器健康状态检测及如何添加第三方扩展模块到此结束,感谢各位博友的关注!!!!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  集群 反向代理 nginx