一:安装nginx前
1:更新系统软件
yum update
2:安装wget
yum install wget
3:安装编译器
yum install gcc gcc-c++
二:安装nginx
1:安装nginx依赖包
nginx的Rewrite模块和HTTP核心模块会使用
到PCRE正则表达式语法:
yum install pcre pcre-devel -y
nginx的各种模块中需要使用gzip压缩:
yum -y install zlib zlib-devel
安全套接字层密码库;
yum -y install openssl openssl-devel
2:下载nginx包并解压(到/usr/local/目录
下)
cd /usr/local/
wget http://nginx.org/download/nginx-
1.12.2.tar.gz
tar -zxvf nginx-1.12.2.tar.gz
3:编译安装(到/usr/local/下)
cd nginx-1.12.2
./configure --prefix=/usr/local/nginx
make && make install
4:创建并设置nginx运行账号:
groupadd nginx
useradd -M -g nginx -s /sbin/nologin nginx
cd /usr/local/nginx/conf
vim nginx.conf,设置user参数如下:
user nginx nginx
5:设置nginx为系统服务
vim /lib/systemd/system/nginx.service
文件内容:
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx-s
reload
ExecStop=/usr/local/nginx/sbin/nginx-s
stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target
6:设置nginx开机自启动
systemctl enable nginx.service
7:开启nginx服务
systemctl start nginx.service
查看nginx是否启动成功
ps aux lgrep nginx
在虚拟机浏览器中访问测试:
http://localhost
出现以下界面表示可以访问:
Welcome to nginx!
Commcrda
Tani you for using igie
8:防火墙开放80端口(nginx默认80端口,
在nginx.conf中配置。)
永久开放80端口:
firewall-cmd -zone=public --add-
port=80/tcp --permanent
重启防火墙:
firewall-cmd --reload
查看防火墙开启状态:
systemctl status firewalld
查看80端口是否开放成功:
firewall-cmd -zone=public --query-
port=80/tcp
在浏览器直接访问虚拟机IP测试是否可以成功
访问
三:实现nginx负载均衡
实现负载均衡需要数台服务器,安装完一台虚
拟机,直接克隆出两台一样的安装环境的虚拟
机
systemctl start nginx.service启动三台虚拟
机上nginx
ip addr查看三台虚拟机的IP地址
负载均衡服务器A:192.168.179.131
web服务器1:192.168.179.132
web服务器2:192.168.179.133
vim /usr/local/nginx/html/index.html
修改内容A为负载均衡服务器
web1为web1处理请求
web2为web2处理请求
打开浏览器输入三台虚拟机IP可以看到刚才修
改的内容
打开负载均衡服务器A的配置文件
vim /usr/local/nginx/conf/nginx.conf
修改内容(添加以下内容):
upstream web-server(
ip_hash;
server 192.168.179.132 fail_timeout
=60s weight=3; #fail_timeout:
这是响应时间,时间长的分配的请求会减少。
server
192.168.179.133 weight=7;
#weight:这是权重,权重
越高,被访问的概率就越大。
server
(
listen 80;
server_name location;
location /(
proxy_pass http://web-server;
root html;
index index.html index.htm;
)
现在在浏览器访问负载均衡服务器A,出现的
内容是:web1处理请求。再刷新之后出现的内
容是:web2处理请求