Nginx+Keepalived+Tomcat之動靜分離的web集羣 php
博客分類: css
webserverhtml
Nginx+Keepalived+Tomcat之動靜分離的web集羣前端
爲小公司提供大概一天持續在100萬/日之間訪問的高性能、高可用、高併發訪問及動靜分離的web集羣方案java
Nginx+Keepalived 高可用、反向代理
Nginx+PHP 高併發、動態解析
Tomcat JSP 動態解析
Apache 穩定的HTML靜態訪問
1、總體介紹:
1.架構圖mysql
本文涉及的幾個知識點:
①:Nginx ②:FastCGI ③:Keepalived ④:tomcat ⑤:LAMP ⑥:Squid ⑦:memcache//後兩個目前不涉及linux
2.爲何要用 nginx
Nginx ("engine x") 是一個高性能的 HTTP 和 反向代理 服務器,也是一個 IMAP/POP3/SMTP 代理服務器。 Nginx 是由 Igor Sysoev 爲俄羅斯訪問量第二的Rambler.ru 站點開發的,它已經在該站點運行超過四年多了。Igor 將源代碼以類BSD許可證的形式發佈。自Nginx 發佈四年來,Nginx 已經由於它的穩定性、豐富的功能集、示例配置文件和低系統資源的消耗而聞名了。目前國內各大門戶網站已經部署了Nginx,如新浪、網易、騰訊等;國內幾個重要的視頻分享網站也部署了Nginx,如六房間、酷6等。新近發現Nginx 技術在國內日趨火熱,愈來愈多的網站開始部署Nginx。nginx
3.Nginx 發佈
當前開發版: Nginx 1.1.5 | Nginx/windows 1.1.5 (更新記錄) (2011年10月6日)
當前穩定版: Nginx 1.0.8 | Nginx/windows 1.0.8 (更新記錄) (2011年10月1日)
歷史穩定版: Nginx 0.8.54 | Nginx/windows 0.8.55 (更新記錄) (2011年7月19日)
歷史穩定版: Nginx 0.7.69 | Nginx/windows 0.7.69 (更新記錄) (2011年7月19日)c++
4.筆者談Nginx
Nginx有低內存佔用,高性能高併發訪問,使得不少新平臺的搭建、舊應用的遷移開始應用nginx,話說nginx不得不說張宴,就像談LVS不得不說章文嵩同樣;
張宴簡歷:
張宴,就任於北京金山軟件公司,金山遊戲官方網站──逍遙網系統架構師,技術支持部平臺組組長。曾在新浪網、趕集網等公司任系統工程師、系統架構師,工做內容主要涉及:服務器系統架構設計與部署、系統運維與調優、網絡故障解決、網站後端以及接口類PHP程序開發、Unix開源軟件二次開發、服務器監控系統開發、系統運維與平臺研發團隊管理。
web
5.學習Nginx用書
一本《實戰Nginx:取代Apache的高性能Web服務器》通俗易懂,不過有些讀者看到後,即提及此書無非就是配置文件的講解,我到反駁,道:nginx之因此這麼強盛的應用,簡單的配置文件和靈活的模塊也是一大亮點,若是你能將部分模塊應用好,那麼你的web服務,將會在訪問速度、服務器性能、硬件成本賽過了競爭對手;
2、Nginx軟件應用部署
1.安裝環境
採用 五臺Centos 5.4 kernel:2.6.18-164.el5xen Server、一臺XP sp3 Client
IP地址分配:
提供域名 www.abc.com
解析地址 VIP:172.17.80.10
front1 內網IP 192.168.1.11
front2 內網IP 192.168.1.12
WebServer集羣:tomcat192.168.1.1七、20 nginx 192.168.1.18 apache192.168.1.19
前端:Nginx 只作高可用和代理
後端:web集羣有 nginx PHP 請求;tomcat 動態jsp .do文件;apache靜態html 等
析:nginx 靜態訪問比較好,apache+php做動態,此處只爲說明LNMP架構的構建!
軟件版本:
nginx: nginx-1.1.6.tar.gz // 下載:www.nginx.org
tomcat: apache-tomcat-7.0.21.tar.gz
JDK: jdk-1_5_0_16-linux-i586.bin
PHP: php-5.3.8.tar.gz //提供FastCGI
apache: httpd-2.2.3-31.el5 // yuminstall httpd php
2.安裝部署 系統環境:
Centos 5.4 製做本地yum源
#mkdir /mnt/cdrom{1,2}
#mount /dev/cdrom /mnt/cdrom1
#cp -r /mnt/cdrom1/* /mnt/cdrom2
#cd /mnt/cdrom2
#rpm -ivh createrepo-0.4.11-3.el5.noarch.rpm
#createrepo -g /mnt/cdrom/repodata/repomd.xml /mnt/cdrom/CentOS/
#vi /etc/yum.repos.d/server.repo
[CentOS]
name=CentOS
baseurl=file:///mnt/cdrom/CentOS
gpgcheck=0
enable=1
#yum -y install gcc openssl-devel zlib-devel pcre-devel
#yum -y install gcc gcc-c++ autoconfautomake //安裝編譯gcc環境
3.nginx的安裝
#tar zxvf nginx-1.1.6.tar.gz
#cd nginx-1.1.6
#useradd -s /sbin/nologin -Mnginx //添加nginx 用戶,沒有登陸shell,沒有家目錄
#./configure \
--prefix=/usr/local/nginx\ //安裝路徑
--sbin-path=/usr/sbin/nginx\ //可執行文件路徑
--conf-path=/etc/nginx/nginx.conf\ //默認爲<prefix>/conf/nginx.conf 最好定義到/etc下
--pid-path=/var/run/nginx/nginx.pid \ //pid文件存放位置,後面將會用到
--error-log-path=/var/log/nginx/error.log\ //錯誤日誌文件,默認爲<prefix>/logs/error.log
--http-log-path=/var/log/nginx/access.log\ //訪問日誌,默認爲<prefix>/logs/access.log
--lock-path=/var/lock/nginx.lock\
--user=nginx \
--group=nginx \
--with-http_stub_status_module\ //以取得一些nginx的運行狀態
--with-http_ssl_module\ //支持https加密鏈接
--with-http_gzip_static_module\ //靜態緩存模塊
--with-http_realip_module \ //讓Nginx透明獲取客戶端IP
--http-client-body-temp-path=/var/tmp/nginx/client/ \ //指定http客戶端請求緩存文件存放目錄
--http-proxy-temp-path=/var/tmp/nginx/proxy/\ //指定http反向代理緩存文件存放目錄
--http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ //指定FastCGI緩存文件存放目錄
#make && makeinstall //安裝nginx
4.編寫SystemV風格的啓動腳本
#vim /etc/init.d/nginxd
############################################
#!/bin/bash
#BY hanfeng
#datetime 20111031
. /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
############################################
保存nginxd腳本,賦予執行權限,添加服務和開機啓動
#chmod +x /etc/init.d/nginxd
#chkconfig --add nginxd
// 若是不支持,則添加一下2行便可
// # chkconfig: - 8515 #爲必須字符
// # description: nginx is a World Wide Web server. It is used to serve
#chkconfig --level 2345 nginxdon
#service nginxdstart //先啓動nginx 看看,沒問題的話就OK了
Starting nginx: [ OK ]
5.在Client上訪問front1上的nginx
http://172.17.80.11
6.將 front1上的nginx scp到front2上,並一樣部署並在安裝後將nginx.conf文件對拷
#scp nginx-1.1.6.tar.gz root@192.168.1.11:/root
#scp /etc/nginx/nginx.conf root@192.168.1.11:/etc/nginx/nginx.conf
3、nginx的動靜分離和負載均衡
1.在front1 、front2 配置
A:動靜分離說明:
有前置nginx 作反向代理,採用nginx的location作動靜分離,將靜態HTML網頁、圖片、JS、CSS等使用後端nginx或apache處理,以便獲得更快的速度;將.jsp、.jspx、.do等交給後端tomcat來處理,
從而實現動靜分離的應用;
B:負載均衡的說明:
此處採用nginx的proxy_pass將location作動靜分離後的jsp、do等jsp程序文件分發到後端upstreamd模塊中tomcat集羣上,rewrite作正則分發,此時也將應用到nginx經典之處的IP哈希(ip_hash)模塊,這樣每一個訪客固定訪問一個後端web服務器,能夠解決session的問題;
2.分別在front1和front2上配置nginx動靜分離和負載均衡
#vi /etc/nginx/nginx.conf
############################################
user nginx nginx;
worker_processes 4;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
upstream tomcat_server {
# ip_hash;
server 192.168.1.17 weight=2;
server 192.168.1.20 max_fails=2fail_timeout=30s;
}
upstream apache_server {
ip_hash;
server 192.168.1.19;
}
upstream nginx_server {
ip_hash;
server 192.168.1.18;
}
server
{
listen 80;
server_name www.abc.com ;
location / {
index index.html index.php index.htm index.jsp index.do default.do;
root html;
if (-d $request_filename)
###############################################
{
rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}
location ~ \.(jsp|jspx|do)?$ {
proxy_set_headerHost %host;
proxy_set_headerX-Forwarded-For $remote_addr;
proxy_pass http://tomcat_server ;
}
###############################################
location ~ \.(php|php5)?$ {
proxy_set_headerHost %host;
proxy_set_headerX-Forwarded-For $remote_addr;
proxy_pass http://nginx_server ;
}
#############################################
location ~ \.(html|htm)?$ {
proxy_set_headerHost %host;
proxy_set_headerX-Forwarded-For $remote_addr;
proxy_pass http://apache_server ;
}
#############################################
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)${
expires 30d;
}
location ~ .*\.(js|css)?$ {
expires 1h;
}
#############################################
}
error_page 404 /404.html;
error_page 500 502 503504 /50x.html;
location = /50x.html {
root html;
}
}
}
############################################
3.重啓nginx服務
#service nginxd restart
Shutting down interface eth0: [ OK ]
Shutting down interface eth1: [ OK ]
Shutting down loopback interface: [ OK ]
Bringing up loopback interface: [ OK ]
Bringing up interface eth0: [ OK ]
Bringing up interface eth1: [ OK ]
4、接下來配置高可用組建keepalived
1.爲何使用keepalived
軟件官網:http://www.keepalived.org
軟件得到:#wget http://www.keepalived.org/software/keepalived-1.2.2.tar.gz
keepalived是一個相似於layer3, 4 & 5交換機制的軟件,也就是咱們平時說的第3層、第4層和第5層交換。Keepalived的做用是檢測web服務器的狀態,若是有一臺web服務器死機,或工做出現故障,
Keepalived將檢測到,並將有故障的web服務器從系統中剔除,當web服務器工做正常後Keepalived自動將web服務器加入到服務器羣中,這些工做所有自動完成,不須要人工干涉,須要人工作的只是修復故障的web服務器。
keepalived和heartbeat的普遍應用足以說明了二者估計是由於本質不一樣而已!
2.分別在front1和front2部署keepalived須要卻分主從關係
#vim /etc/hosts //修改front1 和front2 的hosts文件,保證文件信息相同
172.17.80.11 front1.ha.com front1
172.17.80.12 front2.ha.com front2
3.編譯安裝keepalived
#tar zxvf keepalived-1.2.2.tar.gz
#cd keepalived-1.2.2
#./configure --prefix=/usr/local/keepalived
#make && make install
4.修改Keepalived配置文件
#mkdir /etc/keepalived
#cp /usr/local/keepalived/etc/keepalived/keepalived.conf/etc/keepalived/keepalived.conf
#cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/
#cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
#cp /usr/local/keepalived/sbin/keepalived /usr/sbin/
#chkconfig --level 2345 keepalived on
############################################
@front1上的keepalived.conf
#vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
notification_email {
hanfeng@qq.com
}
notification_email_from hanfeng@qq.com
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_instance VI_1 {
state MASTER
interface eth1
virtual_router_id 51
mcast_src_ip 192.168.1.11
priority 200
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
172.17.80.10
}
}
############################################
@front2上的keepalived.conf
! Configuration File for keepalived
global_defs {
notification_email {
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_instance VI_1 {
state BACKUP
interface eth1
virtual_router_id 51
mcast_src_ip 192.168.1.12
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
172.17.80.10
}
}
############################################
#service keepalived start //啓動keepalived,若是沒有錯誤高可用到此配置完成
5、重量級web集羣資源
1.安裝WebServer之Nginx+PHP
配置服務器IP爲:192.168.1.18
在nginx的基礎上安裝FastCGIのPHP 使其支持動態PHP請求
說明:此處爲 yum installmysql-devel mysql-server php-mysql perl-DBD-MySQL libxml2-devel libart_lgpllibart_lgpl-devel 簡單安裝mysql
安裝後的PHP爲nginx提供php-fpm
①:libevent 事件觸發網絡庫
libevent-2.0.15-stable.tar.gz
#tar zxvf libevent-2.0.15-stable.tar.gz
#cd libevent-2.0.15-stable
#./configure && make && make install
②:libiconv字符編碼轉換
libconv-1.13.1.tar.gz
#tar zxvf libconv-1.13.1.tar.gz
#cd libconv-1.13.1
#./configure && make && make install
③:FastCGIのPHP
php-5.3.8.tar.gz
#tar zxvf php-5.3.8.tar.gz
#cd php-5.3.8
#./configure --prefix=/usr/local/php --with-mysql=/usr/local/mysql--with-mysqli=/usr/local/mysql/bin/mysql_config --with-openssl--enable-fpm --with-libevent-dir=/usr/local/lib --
enable-mbstring --with-freetype-dir --with-jpeg-dir--with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml--with-iconv-dir=/usr/local
@ 你將會看到:Thank you for using PHP
@error while loading shared libraries: libiconv.so.2: cannot open shared objectfile: No such file or directory
#ln -s /usr/local/lib/libiconv.so.2/usr/lib/libiconv.so.2 //作個鏈接防止make時缺乏libiconv.so.2
#ln -s /usr/local/lib/libiconv.so.2 /usr/local/libiconv.so.2
#make ZEND_EXTRA_LIBS='-liconv'
@說明:make的時候加參數ZEND_EXTRA_LIBS='-liconv'是由於編譯時須要iconv庫, 可是configure的時候沒有寫到Makefile中, 還有一種方法是直接修改Makefile, 在連接庫的地方(應該在100行左右)加
上-liconv;或者sed -i 's#-lz -lm-lxml2 -lz -lm -lxml2 -lz -lm -lcrypt#& -liconv#' Makefile;
@久等以後將會看到:Build complete. Don't forget to run 'maketest'. 不等test了,直接make install 安裝
#make install
#cp php-5.3.8/php.ini-production /usr/local/php/etc/php.ini
④接下來配置PHP及其餘文件
#cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf
#vi /usr/local/php/etc/php-fpm.conf
@開啓如下幾項
pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
⑤在後臺啓動 php-fpm,並ps查看進程運行狀況
#/usr/local/php/sbin/php-fpm &
#ps -ef |grep php-fpm
@將其添加到開機自動啓動
#echo "/usr/local/php/sbin/php-fpm &" >> /etc/rc.d/rc.local
⑥.接下來在nginx中配置fastcgi_params 文件
#vi /etc/nginx/fastcgi.conf
@將裏面內容替換爲
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;
#vi /etc/ngnix/nginx.conf
#####
location ~ \.php$ {
root /www;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
#####
location / {
root /html;
index index.php index.html index.htm;
}
##################################
#vi /usr/local/nginx/index.php
<?php
$link=mysql_connect("localhost","root","123456");
if(!$link) echo "FAILD!";
else echo "OK!";
phpinfo();
?>
#service nginxd restart
@優化linux內核參數:
#vi/etc/sysctl.conf // 增長一下內容,並是修改生效
net.ipv4.tcp_max_syn_backlog = 65536
net.core.netdev_max_backlog = 32768
net.core.somaxconn = 32768
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw.reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.ip_local_port_range = 1024 65535
#sysctl-p //使其及時生效
##################################
問題處理:phpinfo 頁面date的解析顯示亂碼!
Warning: phpinfo() [function.phpinfo]:。。。。。。。。。
We selected 'Asia/Chongqing' for 'CST/8.0/no DST' insteadin /usr/local/nginx/html/index.php on line 8
解析:如下是三種方法(任選一種都行):
a、在頁頭使用date_default_timezone_set()設置 date_default_timezone_set('PRC'); //東八時區echo date('Y-m-d H:i:s');
b、在頁頭使用ini_set('date.timezone','Asia/Shanghai');
c、修改php.ini。打開php.ini查找date.timezone 去掉前面的分號修改爲爲:date.timezone =PRC
重啓http服務(如apache2或iis等)便可。
XXX能夠任意正確的值。在我國內:Asia/Chongqing,Asia/Shanghai ,Asia/Urumqi (依次爲重慶,上海,烏魯木齊)港臺地區可用:Asia/Macao ,Asia/Hong_Kong ,Asia/Taipei (依次爲澳門,香港,臺北),新加坡:Asia/Singapore,PRC能夠。
===================================
2.安裝WebServer之tomcat+JDK使其支持動態jsp程序和.do文件
配置服務器IP地址爲:192.168.1.17/20
①:JDK的安裝和部署
#chmod +x jdk-1_5_0_16-linux-i586.bin
#./jdk-1_5_0_16-linux-i586.bin
#mv jdk1.5.0_16 /usr/local/jdk1.5.0_16
#vi.bash_profile //修改環境變量文件,增長一下內容
JAVA_HOME="/usr/local/jdk1.5.0_16"
CLASS_PATH="$JAVA_HOME/bin"
CATALINA_HOME="/usr/local/tomcat-6.0.18"
export JAVA_HOME CATALINA_HOME
#source .bash_profile //使修改的環境變量生效
#tar zxvf apache-tomcat-6.0.18.tar.gz
#mv apache-tomcat-6.0.18 /usr/local/tomcat-6.0.18
#cd /usr/local/tomcat-6.0.18/bin
#./startup.sh
#ps -ef |grep java //啓動tomcat,若是JDK版本支持且環境變量正確的話,此時你的tomcat已經成功了!
3.安裝WebServer之Apache 使其可以很好提供HTML等靜態訪問請求!
說明:此處的Apache 做爲WebServer 只要yum 安裝便可!你也能夠編譯安裝而且組成LAMP架構!筆者很少說了。。。
6、測試。。。
測試環境準備
1.將測試域名www.abc.com 解析到前置機front一、front2的虛擬(virtual)IP上!
在XP客戶端使用瀏覽器http://www.abc.com/index .*測試首頁測試
2.測試要求
測試頁面分別針對前置機nginx的動靜分離和到tomcat上負載均衡
3.分別在對應的WebServer 上製做測試頁面,並用不一樣IE在客戶端測試
①:index.html
This is a html test page, the server address is 192.168.1.19
②:index.php
This is a php test page, the server address is 192.168.1.18
③:index.jsp 和index.do 只作測試頁面,不作具體動態程序
This is a jsp test page, the server address is 192.168.1.17/20
This is a do test page, the server address is 192.168.1.17/20
4.測試故障
此時在客戶機上ping www.abc.com -t 並將front1 的eth1 給ifdown掉!觀察至丟失了一個數據包即恢復了域名到服務器的訪問!
5.在linux 使用ab命令,對前置front一、front2作簡單的壓力測試!
#ab -c 1000 -n 100000 http://www.abc.com/index .*測試頁