Nginx實現負載均衡
實驗環境:RHEL6.0
Server:Server3.example.com
IP:192.168.0.3
1.安裝配置Nginx
所需源碼包:
gperftools:(優化nginx)http://gperftools.googlecode.com/files/gperftools-2.0.tar.gz
openssl:http://www.openssl.org/source/
# yum install
gcc make gcc-c++ -y
解壓zlib、pcre、openssl、gperftools源碼包!
1.1安裝所需組件——pcre(提供rewrite模塊)
【系統默認自帶有pcre,如若提前卸載,則無法編譯安裝】
【源碼包安裝完畢後請勿刪除,因爲安裝nginx時需要使用】
# tar zxf
pcre-8.32.tar.gz
# cd
pcre-8.32
# ./configure
\
>
--prefix=/usr/local/pcre-8.32 \
>
--libdir=/usr/local/lib/pcre \
>
--includedir=/usr/local/include/pcre
# make
&& make install
# vim
/etc/ld.so.conf
***********************************
添加:
/usr/local/lib/pcre
***********************************
# ldconfig #載入動態函數庫
1.2安裝google-perftools
google-perftools包含四個工具:TCMalloc、heap-checker、heap-profiler和cpu-profiler,TCMalloc是google-perftools的其中一個工具,用於優化內存分配的效率和速度,幫助在高併發的情況下很好的控制內存的使用。
# tar zxf
gperftools-2.0.tar.gz
# cd
gperftools-2.0
# ./configure
# make&&make
install
# echo
"/usr/local/lib" >>/etc/ld.so.conf
# ldconfig
1.3安裝Nginx
# useradd -M
-s /sbin/nologin www
# cd
nginx-1.3.14
# ./configure
\
>
--user=www \
>
--group=www \
>
--prefix=/usr/local/nginx \
>
--pid-path=/usr/local/nginx/logs/nginx.pid \
>
--error-log-path=/usr/local/nginx/logs/error.log \
>
--http-log-path=/usr/local/nginx/logs/access.log \
>
--with-http_stub_status_module \ #取得一些nginx的運行狀態
>
--with-http_ssl_module \
>
--http-client-body-temp-path=/tmp/nginx_client \#客戶端請求臨時文件
>
--http-proxy-temp-path=/tmp/nginx_proxy \
>
--http-fastcgi-temp-path=/tmp/nginx_fastcgi \
>
--with-http_gzip_static_module \ #啓用時需要zlib
>
--with-google_perftools_module \ #該模塊能優化nginx
> --with-ld-opt='-l
tcmalloc_minimal' \ #該模塊能優化nginx
>
--with-ipv6 \
> --with-pcre=/root/source/pcre-8.32/ \ #指定pcre的源碼位置
> --with-openssl= /root/source/openssl-1.0.1e \ #指定openssl源碼位置
> --with-zlib=/root/source/zlib-1.2.5
\
#指定zlib的源碼位置
> --with-http_flv_module \
#支持對FLV文件的拖動播放
> --with-http_realip_module \
#支持顯示真實來源IP地址
> --with-mail
\
#允許POP3/IMAP4/SMTP代理模塊
> --with-mail_ssl_module \#允許POP3/IMAP/SMTP可以使用SSL/TLS
#make
#make install
1.4 配置Nginx
# vim /usr/local/nginx/conf/nginx.conf
********************************************************************
user www;
worker_processes 1;
error_log logs/error.log;
pid logs/nginx.pid;
google_perftools_profiles
/var/tmp/tcmalloc;
worker_rlimit_nofile
1024;
events {
use epoll;
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
upstream server3.example.com {
server
192.168.0.4:80
weight=1 max_fails=3 fail_timeout=60s;
server
192.168.0.5:80
weight=1 max_fails=3 fail_timeout=60s;
}
access_log
off;
error_log /dev/null;
sendfile on;
server_names_hash_bucket_size 128;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 8m;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 120;
gzip
on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
#壓縮等級
gzip_types
text/plain
application/x-javascript
text/css application/xml;
gzip_vary
on;
server {
listen 80;
server_name Server3.example.com;
#access_log logs/host.access.log;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
include
vhost/*.conf;
}
1.5配置nginx代理
# cd
/usr/local/nginx/conf/
# vim
proxy.conf
*********************************************************************
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 50m;
client_body_buffer_size
256k;
proxy_connect_timeout 30;
proxy_send_timeout 30;
proxy_read_timeout 60;
proxy_buffer_size 4k;
proxy_buffers 4
32k;
proxy_busy_buffers_size
64k;
proxy_temp_file_write_size 64k;
proxy_next_upstream error timeout invalid_header http_500
http_503 http_404;
proxy_max_temp_file_size 128m;
#Nginx cache
client_body_temp_path client_body 1 2;
proxy_temp_path
proxy_temp 1 2;
#client_body_temp_path /tmpfs/client_body_temp 1 2;
#proxy_temp_path /tmpfs/proxy_temp 1 2;
#fastcgi_temp_path /tmpfs/fastcgi_temp 1 2;
*********************************************************************
1.6建立Ningx虛擬主機目錄
# mkdir -p
/usr/local/nginx/conf/vhost
# mkdir
/home/www
# chmod 755
-R /home/www
# chown -R
www.www /home/www/
# chown www
/usr/local/nginx/conf/
1.7啓動、關閉Nginx
# cp
/usr/local/nginx/sbin/nginx /etc/init.d/nginx
#
/etc/init.d/nginx #啓動Nginx
# /etc/init.d/nginx -s reload #重啓Nginx
#
/etc/init.d/nginx -s stop #關閉Nginx
1.8 Nginx啓動腳本
# vim
/etc/init.d/nginx
********************************************************************
#! /bin/sh
# chkconfig:
2345 55 25
#
Description: Startup script for nginx webserver on RHEL. Place in /etc/init.d
and
# run
'update-rc.d -f nginx defaults', or use the appropriate command on your
# distro. For
CentOS/Redhat run: 'chkconfig --add nginx'
### BEGIN
INIT INFO
#
Provides: nginx
#
Required-Start: $all
# Required-Stop: $all
#
Default-Start: 2 3 4 5
#
Default-Stop: 0 1 6
#
Short-Description: starts the nginx web server
#
Description: starts nginx using
start-stop-daemon
### END INIT
INFO
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="nginx
daemon"
NAME=nginx
DAEMON=/usr/local/nginx/sbin/$NAME
CONFIGFILE=/usr/local/nginx/conf/$NAME.conf
PIDFILE=/usr/local/nginx/logs/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
set -e
[ -x
"$DAEMON" ] || exit 0
do_start() {
$DAEMON -c $CONFIGFILE || echo -n "nginx
already running"
}
do_stop() {
kill -INT `cat $PIDFILE` || echo -n
"nginx not running"
}
do_reload() {
kill -HUP `cat $PIDFILE` || echo -n
"nginx can't reload"
}
case
"$1" in
start)
echo -n "Starting $DESC: $NAME"
do_start
echo "."
;;
stop)
echo -n "Stopping $DESC: $NAME"
do_stop
echo "."
;;
reload|graceful)
echo -n "Reloading $DESC
configuration..."
do_reload
echo "."
;;
restart)
echo -n "Restarting $DESC: $NAME"
do_stop
do_start
echo "."
;;
*)
echo "Usage: $SCRIPTNAME
{start|stop|reload|restart}" >&2
exit 3
;;
esac
exit 0
********************************************************************
# chmod +x
/etc/init.d/nginx
#
chkconfig --add nginx
#
chkconfig nginx on
1.9 虛擬主機的建立
# cd
/usr/local/nginx/conf/vhost/
# vim
default.conf
*********************************************************************
server
{
listen 80;
#本機域名或IP
server_name server3_3.example.com
index index.html
index.php;
root /home/www;
location /nginx{
stub_status on;
auth_basic "NginxStatus";
#auth_basic_user_file conf/htpasswd;
#密碼是由apache的htpasswd工具產生
access_log
off;
}
location / {
location ~ .*/.(php|php5)?$ {
index
index.php;
root
/home/www/;
proxy_pass http://127.0.0.1:81;
}
include
proxy.conf;
if ( !-e
$request_filename){
proxy_pass http://127.0.0.1:81;
}
location ~*
/.(jpg|jpeg|gif|png|swf)$ {
if ( -f
$request_filename ){
root /home/www/;
expires 30d;
break;
}
}
location
~* /.(jss|css)$ {
if (-f
$request_filename){
root /home/www/;
expires 1d;
break;
}
}
}
error_page 500
502 503 504
/50x.html;
location =
/50x.html{
root html;
}
#如果需要記錄就把下面的註釋去掉
#
log_format access
'$http_x_forwarded_for - $remote_user [$time_local]
"$request"'
#
'$status $body_bytes_sent "$http_referer"'
#
'"$http_user_agent" $remote_addr';
#
access_log logs/IP_access.log access;
}
*********************************************************************
注意,配置文件中,每個“server”即就一臺主機~
#
/etc/init.d/nginx start #啓動Nginx
此時,對應關係如下:
server3.example.com——>/usr/local/nginx/html/index.html
server3_3.example.com——>/home/www/index.html
虛擬主機OK了!
多個虛擬主機複製並修改以上內容即可~
順便提一句:
可以利用tcmalloc優化mysql數據庫喔!
# vim
/etc/init.d/mysqld
添加:export
LD_PRELOAD=/usr/local/lib/libtcmalloc.so
重啓mysql數據庫
# lsof -n|grep tcmalloc 可以查看mysql是否採用了該模塊。
2.0 Nginx實施負載均衡(必須配合反向代理才能實現)
主要利用ngx_http_upstream_hash_module模塊和Nginx反向代理配置
# vim /usr/local/nginx/conf/nginx.conf
在http花括號內,添加:
***************************************************************
upstream servertest.example.com {
server
192.168.0.1:80
weight=1 max_fails=3 fail_timeout=60s;
server
192.168.0.2:80
weight=1 max_fails=3 fail_timeout=60s;
}
#其中weight是權重,決定服務器的優先級;
#max_fails的值決定主server判斷slave是否宕機的失敗次數;
#faile_timeout的值決定判定爲宕機的時間(如:60秒內是宕機狀態)
***************************************************************
2.1 Nginx反向代理的設置
反向代理:多個客戶端使用該服務器訪問內部web服務器,從而提升靜態網頁的訪問速度!代理服務其均勻發送請求 多臺內部web服務器,達到較好的負載均衡效果!
反向代理的優勢:
可以將負載均衡和代理服務器的高速緩存技術結合在一起,提供有益的性能,具備額外的安全性,外部用戶不能直接訪問真實的web服務器,並且可以實現較好的負載均衡策略,將負載可以非常均勻地分給內部服務器,不會出現負載集中到某個服務器的偶然現象。
# vim /usr/local/nginx/conf/nginx.conf
*********************************************************************
添加:
server
{
listen
80;
server_name
servertest.example.com;
location / {
proxy_pass
http://servertest.example.com;#反向代理的地址池
proxy_set_header Host
$host;
proxy_set_header X-Real-IP $remote_addr;
}
access_log off;
}
#當後端web服務器上也配置有多個虛擬主機時,需要用Header來區分反向代理哪個主機名;
#如果後端web服務器上的程序需要獲取用戶IP,就從Header頭獲取!
*********************************************************************
對與緩存方面的設置,根據變更頻率的不同而合適的設置即可~
Nginx的配置文件對字體格式要求很嚴,出問題時請注意檢查!
在其它slave機器安裝nginx後進行測試!
遇到的問題及解決辦法:
1.報錯:[emerg]directive "location" has no opening "{"
in .....
解決方法:
由於對應行或者附近行的“{”前面缺少空格,導致該錯誤!
2.無報錯,但是就是無法打開80端口進行工作
解決方法:配置文件中,缺少“server......”項的配置!(就是監聽80端口和根目錄的相關配置)
3.可以使用域名訪問,但是無法使用IP訪問
解決辦法:我是因爲在配置文件中有選項“include vhost/*.conf;”,該選項應該放於文件末尾,否則會覆蓋後面相應的配置!
4.訪問servertest.example.com是報錯“502 Bad Gateway”
解決辦法:出現此問題說明已經正確配置了proxy,負載均衡的機器服務爲開!
找到slave機器重新開啓nginx服務即可!
5.啓動Nginx是報錯:[emerg] unknown directive "}" in nginx.conf
解決方法:nginx不識別的“}”是由於我的疏忽採用了中文輸入法造成的!