实验配置
首先至少准备3台虚拟机,
一台做反向代理,另外两台做负载均衡。我们可以用物理机来访问测试。
nginx服务搭建开始
采用yum 的方式搭建,简单快捷
首先下载epel源
[root@server ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo //我这里下载的是阿里云提供的
下载nginx
[root@server ~]# yum install nginx -y
编辑nginx配置文件
配置upstream和server
[root@server ~]# cd /etc/nginx/
[root@server nginx]# vim nginx.conf
http {
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 /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 4096;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
upstream xiaoxin { #设定负载均衡服务器列表
server 192.168.100.25:80;
server 192.168.100.35:80;
}
server {
listen 80;
listen [::]:80;
server_name 192.168.100.10;
root /usr/share/nginx/html;
location / {
proxy_pass http://xiaoxin; #请求转向xiaoxin定义的服务器列表 和upstream模块后面的命名保持一致
}
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
error_page 404 /404.html;
location = /404.html {
}
......
重启nginx服务
[root@server nginx]# systemctl restart nginx
负载一服务器配置
[root@one ~]# yum install httpd -y
[root@one ~]# echo "192.168.100.25 one">/var/www/html/index.html
[root@one ~]# firewall-cmd --add-port=80/tcp --permanent
success
[root@one ~]# firewall-cmd --reload
success
[root@one ~]# curl 192.168.100.25
192.168.100.25 one
负载二服务器配置
[root@two ~]# yum install httpd -y
[root@two ~]# echo "192.168.100.35 two">/var/www/html/index.html
[root@two ~]# firewall-cmd --add-port=80/tcp --permanent
success
[root@two ~]# firewall-cmd --reload
success
[root@two ~]# systemctl restart httpd
[root@two ~]# curl 192.168.100.35
192.168.100.35 two
测试
可以看到访问代理服务器,显示的内容是负载一和负载二服务器上的内容。
[root@server nginx]# curl 192.168.100.10
192.168.100.25 one
[root@server nginx]# curl 192.168.100.10
192.168.100.35 two
[root@server nginx]# curl 192.168.100.10
192.168.100.35 two
[root@server nginx]# curl 192.168.100.10
192.168.100.25 one
[root@server nginx]# curl 192.168.100.10
192.168.100.35 two