本文是学习nginx记录使用,包含nginx的概念、安装、配置、集群,仅供参考。
文章目录
一、概念
1、什么是nginx?
nginx是一个高性能的http和反向代理服务器,特点是占用内存少,并发能力强,适合作为静态页面的web服务器。
2、什么是正向代理和反向代理?
正向代理:客户直接通过配置的服务器访问资源。
反向代理:客户端将请求发送到反向代理服务器,由反向代理服务器去转发请求到目标服务器,再返回结果给客户端,隐藏真实服务器地址,暴露代理服务器。
3、什么是负载均衡?
负载均衡就是横向解决并发问题的一种方案,通过增加服务器数量将原先集中到单个服务器的请求分配到多个服务器中。
4、动静分离
动静分离:前后端分离,以把动态页面和静态页面由不同的服务器来解析,加快解析速度。降低原来单个服务器的压力。
二、nginx的安装
可以去官网下载需要的安装包,安装环境很多,下面只演示下docker环境安装nginx。
1、使用docker查看nginx版本
docker search nginx
没有指定要求,一般挑选点赞最多的下就可以。
2、下载nginx镜像
docker pull nginx
3、创建挂载的目录
mkdir -p /home/nginx/conf
mkdir -p /home/nginx/log
mkdir -p /home/nginx/html
4、复制nginx的配置到目录下
运行容器
docker run -d --name nginx01 -p 8088:80 nginx
复制配置文件到之前建好的目录下面
docker cp nginx:/etc/nginx/nginx.conf /home/nginx/conf/nginx.conf
docker cp nginx:/etc/nginx/conf.d /home/nginx/conf/conf.d
docker cp nginx:/usr/share/nginx/html /home/nginx/
5、重新启动容器挂载配置文件运行
停止运行
docker stop nginx
删除容器
docker rm nginx
运行容器
docker run \
-p 8091:80 \
--name nginx \
-v /home/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /home/nginx/conf/conf.d:/etc/nginx/conf.d \
-v /home/nginx/log:/var/log/nginx \
-v /home/nginx/html:/usr/share/nginx/html \
-d nginx
6、测试(记得开放端口号)
三、nginx的配置
1、并发数的配置
一般和CPU数相同
2、网络连接数
3、http块(全局和serve)
3.1 、反向代理
server {
#nginx监听端口和服务器
listen 80;
server_name localhost;
#静态资源访问路径
location / {
root html/dist;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# 反向代理,通过dev标识处理管理端发送的请求,代理到目标服务器
location /dev/ {
proxy_pass http://webservers/admin/;
}
# 反向代理,通过user标识处理用户端发送的请求
location /user/ {
proxy_pass http://webservers/user/;
}
}
3.2、负载均衡
http {
upstream testserver{
server 服务器地址
server 服务器地址
}
location / {
root html;
proxy_pass http://testserver
index index.html index.htm;
}
负载均衡策略主要由三种,轮询、最少链接和iphash。默认是轮询方式。
轮询: 循环发送请求,可以增加请求权重server 服务器 weight=1;
iphash: 每个请求按访问 ip 的 hash 结果分配,这样每个访客固定访问一个后端服务器
最少连接 : 请求分配给活动连接数最少的服务器,哪台服务器连接数最少,则把请求交给哪台服务器
四、nginx集群
提供一台备用服务器,和虚拟ip,访问虚拟ip当主服务器挂了,通过脚本连到第二台服务器。此处采用采用 keepalived 和 Nginx实现高可用,前者是一个路由中间件,作用是在nginx不可用时改路由。
1、安装keepalived
yum install keepalived –y
#查找配置文件
whereis keepalived
2、keepalived配置文件
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.17.129
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_http_port {
script "/usr/local/src/nginx_check.sh"
interval 2 #(检测脚本执行的间隔)
weight 2
}
vrrp_instance VI_1 {
state BACKUP # 备份服务器上将 MASTER 改为 BACKUP
interface ens33 //网卡
virtual_router_id 51 # 主、备机的 virtual_router_id 必须相同
priority 90 # 主、备机取不同的优先级,主机值较大,备份机值较小
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.17.50 // VRRP H 虚拟地址
}
}
3、添加检测脚本
#!/bin/bash
A=`ps -C nginx –no-header |wc -l`
if [ $A -eq 0 ];then
/usr/local/nginx/sbin/nginx
sleep 2
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killall keepalived
fi
fi
添加路径在第2步骤你自己设置的script位置。