实验目的:实现Nginx的负载均衡和动静分离
实现环境:一台server用作Nginx代理(需要两块网卡,eth0连接内网,eth1连接外网),两台用作web服务(每台server都定义两个虚拟机,端口分别是80和8080),一台客户端用于验证结果;
操作步骤
负载均衡的实现:
一、配置IP
1.配置A主机的IP
# ip addr add dev eth0 192.168.10.254/24
# ip addr add dev eth1 192.168.20.254/24
2.配置B主机的IP
# ip addr add dev eth0 192.168.10.2/24
3.配置C主机的IP
# ip ddr add dev eth0 192.168.10.3/24
二、配置web服务(B和C主机都做同样配置)
1.安装所需程序包
# yum -y install nginx php-fpm
2.配置web服务,提供默认主页
# vim /etc/nginx/conf.d/defalut.conf
server {
index index.php index.html;
}
location / {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
include fastcgi_params;
}
# vim /usr/share/nginx/html/index.php
<?php
phpinfo();
?>
3.将php-fpm的运行用户和组改为nginx
# vim /etc/php-fpm.d/www.conf
user = nginx
group = nginx
4.启动php-fpm和nginx
# service php-fpm start
# service nginx start
三、配置代理,以集群方式实现负载均衡
1.安装nginx
# yum -y install nginx
2.定义动态页面集群组,在http{}段中定义;
# vim /etc/nginx/nginx.conf
http {
upstream websrvs {
server 192.168.10.2:80;
server 192.168.10.3:80;
}
}
3.调用定义的集群组,在server{}段的location{}段中调用;
# vim /etc/nginx/conf.d/default.conf
server {
location / {
proxy_pass http://wersrvs;\
index index.php;
}
}
4.启动服务
# service nginx start
5.在客户端上测试,访问192.168.20.254地址,响应的服务器是轮询的结果;
动静分离的实现:
一、配置虚拟主机
1.配置虚拟主机(B和C主机都作同样配置,默认主页中的ip地址改为C主机的ip,以示区分)
# vim /etc/nginx/conf.d/default.conf
server {
listen 8080;
server_name _;
index index.html
location / {
root /var/www/static;
}
}
2.创建默认主页
# mkdir -v /var/www/static
# vim /var/www/static/index.html
<h1>static page 192.168.10.2</h1>
3.检测和重载配置
# nginx -t
# nginx -s reload
二、定义静态页面集群组及调用
1.定义静态页面集群组
# vim /etc/nginx/nginx.conf
http {
upstream statrvs {
server 192.168.10.2:8080;
server 192.168.10.3:8080;
}
}
2.调用定义的集群组,在server{}段的location{}段中调用;
# vim /etc/nginx/conf.d/default.conf
server {
location ~* \.(jpg|jpeg|png|gif|html)$ {
index index.html;
}
}
结果验证:
1.访问静态页面,在浏览器中输入地址:192.168.20.254/index.html,此时响应的集群组是stasrvs,且后端的服务器轮询响应请求;
2.访问动态页面,在浏览器中输入地址:192.168.20.254/index.php,此时响应的集群组是websrvs,且后端的服务器轮询响应请求;
原创文章,作者:人字拖,如若转载,请注明出处:http://www.178linux.com/75483