192.168.10.147作nginx前端代理服務器,192.168.10.140作後端lamp1,192.168.10.148作lamp2,mysql服務器安裝在140上,148作爲一個數據庫客戶端來訪問140,如今要實現的需求是訪問192.168.10.147會自動均衡到後端的兩臺lamp上,而且訪問靜態頁面直接從本地的nginx來解析,訪問動態頁面會發送到後端的lampcss
1、安裝環境html
在147上操做:前端
下載nginx wget http://nginx.org/download/nginx-1.4.7.tar.gzmysql
tar –zxvf nginx-1.4.7.tar.gznginx
cd nginx-1.4.7web
yum install pcre-devel -y 安裝pcre庫,支持rewrite 重寫sql
注:安裝源碼的pcre時,指定pcre路徑爲解壓的路徑,而不是編譯後的路徑,不然會報錯數據庫
yum install -y openssl-develapache
useradd -s /sbin/nologing -M www後端
./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
make && make install
在140和148上搭建好lamp環境,能夠參考http://pc1990.blog.51cto.com/10541224/1682753
在140上操做
搭建discuz論壇:
mysql #進入mysql數據庫
grant all on discuz.* todiscuz@'192.168.10.140' identified by '123456';
##建立一個普通用戶discuz,並給它discuz數據庫的全部權限
grant all on discuz.* todiscuz@'192.168.10.148' identified by '123456';
給148一樣的權限
將discuz論壇的源碼放到/usr/local/apache/htdocs/ 下,並將htdocs的目錄的所屬主,所屬組改成運行apache的帳戶,而後安裝便可
安裝完成後在140上把網站源代碼同步到148上:
rsync -r /usr/local/apache/htdocs/* root@192.168.10.148:/usr/local/apache/htdocs/
而後在148上把htdocs目錄的所屬主,所屬組改成運行apache的帳戶
這時候訪問140和148時候都是同一個論壇
2、作負載均衡:
147上編輯nginx的配置文件/usr/local/nginx/conf/nginx.conf
加入一段:
upstream web1 {
server 192.168.10.140 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.10.148 weight=1 max_fails=2 fail_timeout=30s;
}
啓用代理:
而後保存配置文件,啓動nginx /usr/local/nginx/bin/nginx
這時候訪問192.168.10.147,就會將請求平均分配給後端的lamp了
3、作動靜分離
先將網站代碼文件拷貝一份到nginx的發佈目錄
rsync -r /usr/local/apache/htdocs/* root@192.168.10.147:/usr/local/nginx/html/
編輯nginx配置文件,在server模塊下加一段location匹配靜態文件走本地解析:
保存,從新加載nginx的配置文件/usr/local/nginx/sbin/nginx -s reload
這樣靜態就會走本地的nginx解析,其餘文件就會走後端的代理
能夠作個實驗,在147和140,148上各作個靜態文件1.html,分別寫入
this is 147 this is 140 this is 148
而後訪問192.168.10.147/1.html,不管怎麼訪問都是this is 147,若是把147上的1.html刪掉,就會404,這是由於靜態文件只會走本地nginx來解析,不會走代理。至此nginx負載均衡,動靜分離作完
附:完整的nginx配置文件以下:
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream web1 { server 192.168.10.140 weight=1 max_fails=2 fail_timeout=30s; server 192.168.10.148 weight=1 max_fails=2 fail_timeout=30s; } server { listen 80; server_name localhost; location / { root html; index index.html index.htm; 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://web1; } location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ { root /usr/local/nginx/html; expires 1d; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }