Nginx的搭建和优化

一、Nginx简介1.1概述Nginx:

Nginx是一个高性能的HTTP和反向代理服务器。

是一款轻量级的高性能的web服务器/反向代理服务器/电子邮件(IMAP/POP3)代理服务器

单台物理服务器可支持30 000~50 000个并发请求。

Apache:

Apache是以进程为基础的结构,进程要比线程消耗更多的系统开支,不太适用于多处理器环境,因此,在一个apache Web站点扩容时,通常是增加服务器或扩充群集节点而不是增加处理器。

1.2 Nginx和Apache的优缺点比较(1)nginx相对于apache的优点∶

轻量级,同样起web服务,比apache占用更少的内存及资源

抗并发,nginx处理请求是异步非阻塞的,而apache是阻塞型的在高并发下,nginx能保持低资源低消耗高性能

高度模块化的设计,编写模块相对简

(2)apache相对于nginx的优点∶

Rewrite比nginx的rewrite强大 (rewrite的主要功能就是实现统一资源定位符URL的跳转)

模块多,基本想到的都可以找到

少bug, nginx的bug相对较多

超稳定

存在的理由:一般来说,需要性能的web服务,用nginx。若不需要性能只求稳定,就选用apache。

1.3Nginx作为web服务器与Apache比较相比apache,nginx使用更少的资源,支持更多的并发连接,体现更高的效率。

Nginx作为负载均衡服务器:nginx既可以在内部直接支持rails和php程序对外进行服务,也可以支持http代理服务器对外进行服务。

Nginx采用C进行编写,不论是系统资源开销还是CPU使用效率都比较好。

作为邮件代理服务器:最早开发这个产品的目的之一也是作为邮件代理服务器。

1.4nginx配置简洁, apache较复杂1.5Nginx和Apache最核心的区别apache是同步多进程模型,一个连接对应一个进程,nginx是异步的,多个连接可以对应一个进程。

Nginx处理静态文件好,耗费内存少,只适合静态和反向。

Apache在处理动态有优势,

nginx并发性比较好,CPU占用内存低,如果rewrite频繁,选用apache最佳。

总的来说,apache依然是大部分公司的首选。

二.Linux中的I/O

I/O在计算机中指Input/Output,lOPS (Input/Output Per Second)即每秒的输入输出量(或读写次数),是衡量磁盘性能的主要指标之一。IOPS是指单位时间内系统能处理的I/O请求数量,一般以每秒处理的IO请求数量为单位,I/O请求通常为读或写数据操作请求。

一次完整的I/O是用户空间的进程数据与内核空间的内核数据的报文的完整交换,但是由于内核空间与用户空间是严格隔离的,所以其数据交换过程中不能由用户空间的进程直接调用内核空间的内存数据,而是需要经历一次从内核空间中的内存数据copy到用户空间的进程内存当中,所以简单说I/O就是把数据从内核空间中的内存数据复制到用户空间中进程的内存当中。

磁盘I/O:buff/cache 的区别

 网络I/O:一切皆文件,本质为对socket文件的读写

获取请求数据,客户端与服务器建立连接发出请求,服务器接受请求(1-3)构建响应,当服务器接收完请求,并在用户空间处理客户端的请求,直到构建响应完成(4)返回数据,服务器将已构建好的响应再通过内核空间的网络I/0发还给客户端(5-7)

同步/异步:关注的是消息通信机制,即调用者在等待一件事情的处理结果时,被调用者是否提供完成状态的通知。

同步: synchronous,被调用者并不提供事件的处理结果相关的通知消息,需要调用者主动询问事情是否处理完成

异步: asynchronous,被调用者通过状态、通知或回调机制主动通知调用者被调用者的运行状态

阻塞/非阻塞:关注调用者在等待结果返回之前所处的状态

阻塞: blocking,指IO操作需要彻底完成后才返回到用户空间,调用结果返回之前,调用者被挂起,干不了别的事情。

非阻塞: nonblocking,指IO操作被调用后立即返回给用户一个状态值,而无需等到IO操作彻底完成,在最终的调用结果返回之前,调用者不会被挂起,可以去做别的事情。

 异步非阻塞I/O模型

三、 Nginx的编译安装步骤详解

3.1关闭防火墙,安装依赖关系包

1. #关闭防火墙[root@localhost opt]#systemctl stop firewalld[root@localhost opt]#setenforce 02. #安装依赖关系包[root@localhost opt]#yum -y install pcre-devel zlib-devel gcc gcc-c++ make

3.2新建用户 和组便于管理

3. #新建用户 nginx 服务程序默认 以 nobody 身份运行,建议为其创建专门的用户账户,以便更准确的控制访问权限[root@localhost opt]#useradd -M -s /sbin/nologin nginx

3.3 将压缩包传入到/opt目录下 ,编译安装

4.#切换至opt目录,将下载好的压缩包传进来[root@localhost opt]#cd /opt[root@localhost opt]#lsnginx-1.12.0.tar.gz5.#解压文件[root@localhost opt]#tar -zxf nginx-1.12.0.tar.gz [root@localhost opt]#lsnginx-1.12.0 nginx-1.12.0.tar.gz6.#切换至解压后的文件夹编译[root@localhost nginx-1.12.0]#./configure \> --prefix=/usr/local/nginx \> --user=nginx \> --group=nginx \> --with-http_stub_status_module//解释--prefix=/usr/local/nginx \#安装路径--user=nginx \#指定用户名--group=nginx \#指定用户组--with-http_stub_status_module#启用此模块支持状态统计//7.#安装[root@localhost nginx-1.12.0]#make && make install -j4

3.4做软连接并启动nginx

8. #做软连接,让系统识别nginx的操作命令[root@localhost sbin]#ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/9. #检查配置文件是否配置 正确 [root@localhost sbin]#nginx -t10. #启动nginx[root@localhost sbin]#nginx 11. #查看是否启动成功[root@localhost sbin]#ss -ntap|grep nginxLISTEN 0 128 *:80 *:* users:(("nginx",pid=9123,fd=6),("nginx",pid=9122,fd=6))

3.5停止nginx

1. #先查看nginx的PID号[root@localhost sbin]#cat /usr/local/nginx/logs/nginx.pid 91222.#直接杀死kill -3 <PID号> [root@localhost sbin]#kill -3 9122#就查不到进程了[root@localhost logs]#ss -ntap|grep nginx#一定要杀父进程,杀死子进程是没用的 #查进程号[root@localhost logs]#lsof -i :80COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEnginx 10298 root 6u IPv4 68323 0t0 TCP *:http (LISTEN)nginx 10299 nginx 6u IPv4 68323 0t0 TCP *:http (LISTEN)#查看主进程[root@localhost logs]#cat /usr/local/nginx/logs/nginx.pid 10298#杀死子进程[root@localhost logs]#kill -3 10299 #进程没有杀死[root@localhost logs]#cat /usr/local/nginx/logs/nginx.pid 10298#杀死父进程[root@localhost logs]#kill -3 10298#进程杀死了[root@localhost logs]#cat /usr/local/nginx/logs/nginx.pid #进程杀死了cat: /usr/local/nginx/logs/nginx.pid: 没有那个文件或目录

3.6 添加nginx系统服务

3.6.1法一:编写脚本

#编写脚本内容如下[root@localhost init.d]#vim /etc/init.d/nginx cmd="/usr/local/nginx/sbin/nginx"pid="/usr/local/nginx/logs/nginx.pid" start)$cmd;;stop)kill -3 `cat $pid`;;restart)$0 stop$0 start;;reload)kill -1 `cat $pid`;;*)echo "please input,start,reload,restart "exit 0;;esacexit 1#执行脚本[root@localhost init.d]#chmod +x /etc/init.d/nginx [root@localhost init.d]#chkconfig --add nginx #启动nginx[root@localhost init.d]#service nginx start #关闭nginx[root@localhost init.d]#service nginx stop

3.6.2将nginx命令加入服务

[root@localhost system]#cd /lib/systemd/system#编写脚本,建议直接复制[root@localhost system]#vim nginx.service#!/bin.bash[Unit]Description=nginxAfter=network.target[Service]Type=forkingPIDFile=/usr/local/nginx/logs/nginx.pidExecStart=/usr/local/nginx/sbin/nginxExecReload=/usr/bin/kill -s HUP $MAINPIDExecStop=/usr/bin/kill -s QUIT $MAINPIDPrivateTmp=true[Install]WantedBy=multi-user.target##磁盘上的ngin服务更改,运行'systemctl daemon-reload'重新加载单元。[root@localhost system]#systemctl daemon-reload ##启动服务[root@localhost system]#systemctl start nginx

3.7查看nginx版本信息

[root@localhost system]#nginx -vnginx version: nginx/1.12.0

四、Nginx配置文件

4.1 nginx服务的主配置文件

[root@localhost system]#vim /usr/local/nginx/conf/nginx.conf

4.2全局配置

#user nobody; ##运行用户worker_processes 1; ##工作进程数,可配置成服务器内核数*2,如果网站访问量不大,一般设为1就够用了#error_log logs/error.log; ####错误日志文件的位置#pid logs/nginx.pid; ####PID文件的位置

4.3I/O 事件配置

events { use epoll; #使用 epoll 模型以提高性能,2.6 以上版本建议使用 worker_connections 4096; #每个进程处理4096个连接}

epoll(socket描述符)是Linux内核]为处理大批量文件描述符而作了改进的poll,是Linux下多路复用IO接口select/poll的增强版本,它能显著提高程序在大量并发连接中只有少量活跃的情况下的系统CPU利用率

若工作进程数为 8,每个进程处理 4 096 个连接,则允许 Nginx 正常提供服务的连接数 已超过 3 万个(4 096×8=32 768),当然具体还要看服务器硬件、网络带宽等物理条件的性 能表现。

1.如提高每个进程的连接数还需执行"ulimit -n 65535"命令临时修改本地每个进程可以同时打开的最大文件数。

2.在Linux平台.上,在进行高并发TCP连接处理时,最高的并发数量都要受到系统对用户单一进程同时可打开文件数量的限制(这是因为系统为每个TCP连接都要创建一个socket句柄,每个socket句柄同时也是一个文件句柄)。

3.可使用ulimit -a命令查看系统允许当前用户进程打开的文件数限制。

#查看系统允许当前用户进程打开的文件数[root@localhost conf]#ulimit -acore file size (blocks, -c) 0data seg size (kbytes, -d) unlimitedscheduling priority (-e) 0file size (blocks, -f) unlimitedpending signals (-i) 6911max locked memory (kbytes, -l) 64max memory size (kbytes, -m) unlimitedopen files (-n) 1024pipe size (512 bytes, -p) 8POSIX message queues (bytes, -q) 819200real-time priority (-r) 0stack size (kbytes, -s) 8192cpu time (seconds, -t) unlimitedmax user processes (-u) 6911virtual memory (kbytes, -v) unlimitedfile locks (-x) unlimited#临时修改本地每个进程可以同时打开的最大文件数[root@localhost conf]#ulimit -n 6000#查看修改后的[root@localhost conf]#ulimit -acore file size (blocks, -c) 0data seg size (kbytes, -d) unlimitedscheduling priority (-e) 0file size (blocks, -f) unlimitedpending signals (-i) 6911max locked memory (kbytes, -l) 64max memory size (kbytes, -m) unlimitedopen files (-n) 6000pipe size (512 bytes, -p) 8POSIX message queues (bytes, -q) 819200real-time priority (-r) 0stack size (kbytes, -s) 8192cpu time (seconds, -t) unlimitedmax user processes (-u) 6911virtual memory (kbytes, -v) unlimitedfile locks (-x) unlimited

4.3http配置

使用“http { }”界定标记,包括访问日志、HTTP 端口、网页目录、默认字符集、连接保 持,以及后面要讲到的虚拟 Web 主机、PHP 解析等一系列设置,其中大部分配置语句都包 含在子界定标记“server { }”内

http { include mime.types; ##文件扩展名与文件类型映射表 default_type application/octet-stream; ##默认文件类型 ##日志格式设定 #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 logs/access.log main; #日志格式设定 sendfile on; ##支持文件发送(下载) ##此选项允许或禁止使用socket的TCP cORK的选项(发送数据包前先缓存数据),此选项仅在使用sendfile的时候使用 #tcp_nopush on; ##连接保持超时时间,单位是秒 #keepalive_timeout 0; keepalive_timeout 65; #gzip on; ##gzip模块设置,设置是否开启gzip压缩输出server { listen 80; ##监听地址及端口 server_name www.yxp.com; ##站点域名,可以有多个,用空格隔开 #charset utf-8; #网页的默认字符集 #access_log logs/host.access.log main; location / { ##根目录配置 root html; ##网站根目录的位置/usr/local/nginx/html index index.html index.htm; ##默认首页文件名 } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; ##内部错误的反馈页面 location = /50x.html { ##错误页面配置 root html; }

 

4.4访问状态统计配置nginx 内置了 HTTP_STUB_STATUS 状态统计模块,用来反馈当前的 Web 访问情况, 配置编译参数时可添加--with-http_stub_status_module 来启用此模块支持,可以使用命令

可以使用命令/usr/local/nginx/sbin/nginx –v 查看已安装的 Nginx 是否包含 HTTP_STUB_STATUS 模块。

操作步骤:

1.修改 nginx.conf 配置文件,指定访问位置并添加 stub_status 配置(修改之前进行备份)

#先拷贝一份配置文件[root@localhost conf]#cp /usr/local/nginx/conf/nginx.conf nginx.conf.bak# 修改 nginx.conf 配置文件[root@localhost conf]#vim /usr/local/nginx/conf/nginx.confevents { use epoll; worker_connections 1024;} server { listen 80; server_name www.yxp.com; charset utf-8; location / { root html; index index.html index.htm; } location /status { ##访问位置为/status stub_status on; ##打开状态统计功能 access_log off; ##关闭此位置的日志记录 }

 

 2.在网页中输入 192.168.59.108/status 测试

Active connections: 2 server accepts handled requests 2 2 4 Reading: 0 Writing: 1 Waiting: 1

 3.结合awk来写shell脚本,如果链接数过高报警

#/bin/basha=$(curl 192.168.59.108/status)b=$(echo $a|awk '{print $3}')if [ $b -ge 1000 ]then echo "连接数过高"|mail -s test 1943466298@qq.comelseecho "运行良好"fi

4.5基于授权密码的访问控制

1.生成用户密码认证文件

#安装工具[root@localhost conf]#yum install -y httpd-tools.x86_64 #如果没有密码则设置[root@localhost conf]#htpasswd -c /usr/local/nginx/passwd.db zhangsan#第二次不用加-c[root@localhost conf]#htpasswd /usr/local/nginx/passwd.db lisi[root@localhost conf]#chown nginx /usr/local/nginx/passwd.db[root@localhost conf]#chmod 400 /usr/local/nginx/passwd.db

 1.修改主配置文件相应的目录

location /status { #添加密码认证 auth_basic "secret"; auth_basic_user_file /usr/local/nginx/passwd.db; # stub_status on; # access_log off; root html; index index.html index.htm; }

 2.重启服务

[root@localhost conf]#nginx -t[root@localhost conf]#systemctl restart nginx.service

4.在网页测试

http://192.168.59.108需要输入账号和设置的密码才能登录

4.6基于客户端的访问控制1、基于客户端的访问控制简介 基于客户端的访问控制是通过客户端 IP 地址,决定是否允许对页面访问。Nginx 基于 客户端的访问控制要比 Apache 简单,规则如下: 1)deny IP/IP 段:拒绝某个 IP 或 IP 段的客户端访问。 2)allow IP/IP 段:允许某个 IP 或 IP 段的客户端访问。 3)规则从上往下执行,如匹配则停止,不再往下匹配。

1.修改配置文件

[root@localhost conf]#vim /usr/local/nginx/conf/nginx.conf location / { #auth_basic "secret"; #auth_basic_user_file /usr/local/nginx/passwd.db; deny 192.168.59.130; ###客户端IP allow all; root html; index index.html index.htm; }

 2.重启服务,访问测试

4.7基于域名的nginx 虚拟主机利用虚拟主机,不用为每个要运行的网站提供一台单独的 Nginx 服务器或单独运行一 组 Nginx 进程,虚拟主机提供了在同一台服务器,同一组 Nginx 进程上运行多个网站的功 能。跟 Apache 一样,Nginx 也可以配置多种类型的虚拟主机,分别是基于 IP 的虚拟主机、 基于域名的虚拟主机、基于端口的虚拟主机。 使用 Nginx 搭建虚拟主机服务器时,每个虚拟 Web 站点拥有独立的“server{}”配置段, 各自监听的 IP 地址、端口号可以单独指定,当然网站名称也是不同的。

1.为虚拟主机创建文档

[root@localhost html]#mkdir -p /var/www/html/{yxp,accp}
[root@localhost html]#echo "<h1>www.yxp.com</h1>" > /var/www/html/yxp/index.html
[root@localhost html]#echo "<h1>www.accp.com</h1>" > /var/www/html/accp/index.html

2.修改配置文件

vim /usr/local/nginx/conf/nginx.conf server { listen 80; server_name www.accp.com; charset utf-8; access_log logs/www.accp.access.log; location / { root /var/www/html/accp; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; }} server { listen 80; server_name www.yxp.com; charset utf-8; access_log logs/yxp.access.log; location / { root /var/www/html/yxp; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; }}

 

3.重启服务,并测试

此时域名无法使用,需要修改/etc/hosts配置文件

C:\Windows\System32\drivers\etc\hosts

 

4.8基于IP地址

1.修改配置文件

 

[root@localhost html]#vim /usr/local/nginx/conf/nginx.confserver { listen 192.168.59.108:80; server_name www.yxp.com;server { listen 192.168.59.111:80; server_name www.accp.com;

4.9基于端口

[root@localhost html]#vim /usr/local/nginx/conf/nginx.confserver { listen 192.168.59.108:80; server_name www.yxp.com;server { listen 192.168.59.108:8080; server_name www.accp.com;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值