前言

nginx是一款高性能、轻量级的web服务器、反向代理服务器,由于处理并发能力强,被大量运用在当今的互联网项目中,平均每三个网站就有一个使用nginx的。并且nginx有庞大的nginx中文开源社区以及相当多的活跃用户,出现问题可以及时在社区中寻找解决方案,更不用担心自己部署的nginx在哪一天跑路了。


一、nginx安装及配置前工作

1.准备一台linux系统的机器,我使用的是虚拟机centos7.9纯净版,并设置为静态ip,配置可上网,关闭防火墙等。

配置虚拟机ip,网卡等:

vi /etc/sysconfig/network-scripts/ifcfg-ens33

2.安装nginx
由于nginx是使用c语言开发的,所以安装nginx需要有c语言编译库,这里使用gcc。

yum install -y gcc

还需要一些其他库来支持nginx:一并安装即可

yum install -y pcre pcre-devel
yum install -y zlib zlib-devel

然后准备nginx源码压缩包在这里插入图片描述
解压,执行安装即可

tar zxvf nginx-1.21.6.tar.gz
cd nginx-1.21.6
./configure --prefix=/usr/local/nginx  # --prefix=/usr/local/nginx 指安装路径是/usr/local/nginx
make
make install

3.启动ngin及配置nginx开机启动
cd到/usr/local/nginx/sbin目录下

./nginx					    # 启动nginx

这样启动显然比较麻烦,我们可以编写一个脚本来让成为系统服务。先来创建一个nginx.service文件

vi /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx - web server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload	#重启nginx
ExecStop=/usr/local/nginx/sbin/nginx -s stop	#停止
ExecQuit=/usr/local/nginx/sbin/nginx -s quit	#优雅停止nginx
PrivateTmp=true

[Install]
WantedBy=multi-user.target

然后重新加载系统服务

systemctl daemon-reload

就可以使用systemctl start nginx来启动nginx

systemctl enable nginx.service	#设置开机启动

二、nginx的目录结构

nginx安装完后,没有运行过的话,初始会有四个文件夹,分别是logs(日志文件)、html(页面)、conf(配置文件)和sbin(启动程序)。相比大家已经猜到,负载均衡配置主要是去修改conf文件夹下的nginx.conf
在这里插入图片描述

三、配置负载均衡

负载均衡有多种实现方式:轮询,ip hash、随机等等算法,现在常用的是轮询式。
我们先将上边配置好的nginx机器克隆三台。,其中一台为主机器,负责负载其他三台机器。
下面是nginx.conf文件,修改server中的一些属性即可。

	upstream loadB{
		server 192.168.174.202:80;
		server 192.168.174.203:80;
		server 192.168.174.204:80;
  	}
  	server {
        listen       80;
        server_name  localhost;

        location / {

		proxy_pass http://loadB;
        #     root   html;
        #    index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
        root   html;
        }
}

我们还可以通过设置权重(weight)的方式来控制每台机器的负载量,如果一台机器的带宽很大,可以将其权重设高一点。

	server 192.168.174.202:80 weight=7;
	server 192.168.174.203:80 weight=2;
	server 192.168.174.204:80 weight=1;

还可以通过hash来实现负载均衡,除了ip hash还有cookie hash和request_uri(用户请求资源地址) hash来实现负载均衡,cookie和request_uri与ip地址一样,都具有唯一性:在pc端,不同用户访问浏览器cookie不同;在一些没有cookie的网站,或者不支持cookie(比如app端),在请求资源地址时,通过在资源路径后边加上json来保持会话,使用不同uri访问服务器,hash后的结果也不一样。
在这里插入图片描述
uri
nginx.conf中的配置如下:

upstream loadB{
		hash $cookie_jessionid;
		hash $request_uri;
		
		server 192.168.174.202:80;
		server 192.168.174.203:80;
		server 192.168.174.204:80;
  	}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐