Blog

Make it work, make it right, make it fast

May 25, 2021 - 1 minute read - Nginx

Nginx概览

Nginx(发音同"engine X")是异步框架的 网页服务器,也可以用作 反向代理负载平衡器HTTP缓存。该软件由 伊戈尔·赛索耶夫创建并于2004年首次公开发布。2011年成立同名公司以提供支持。2019年3月11日,Nginx公司被F5 Networks以6.7亿美元收购。

—— 维基百科

特点

占用内存小:得益于C语言编写,Nginx占用内存小、并发量高(Nginx在官方测试的结果中,能够支持五万个并行连接,而在实际的运作中,可以支持二万至四万个并行连接。)。

高并发:在Linux系统上Nginx使用了Epoll机制,能够高效的处理大量的连接数。

高可靠:Ngxin使用了Master-Worker机制,真正处理请求的是Worker进程,Master进程可以监控Worker进程,并且能在Woker进程意外退出的时候重启该进程。

作用

负载均衡

负载均衡示意图

手动安装

打开 官网,从上到下依次是开发版本、稳定版本、过期版本

Nginx版本

下载并解压缩

ubuntu@VM-0-6-ubuntu:~$ wget http://nginx.org/download/nginx-1.20.0.tar.gz
ubuntu@VM-0-6-ubuntu:~$ tar -zxvf nginx-1.20.0.tar.gz

解压缩结果

编译源代码

Linux 的软件在编译的时候要经过三个步骤,configure/make以及make install

1)通用配置选项

配置参数

2)第三方模块

可以使用–without-xxx_module取消自动编译,也可以使用–with-xxx_module添加编译

开始编译

ubuntu@VM-0-6-ubuntu:~/nginx-1.20.0$ ./configure
....
....
./configure: error: the HTTP rewrite module requires the PCRE library.
You can either disable the module by using --without-http_rewrite_module
option, or install the PCRE library into the system, or build the PCRE library
statically from the source with nginx by using --with-pcre=<path> option.

可以看到缺少PCRE(C语言编写的一个正则表达式库,在Nginx中用于http rewrite)模块,上述报错信息给出了三种解决方式:

  • 禁用rewrite 模块
  • 将PCRE 模块安装到默认的系统目录中
  • 使用源码编译PCRE ,将编译后的文件放到自定义的目录中,在configure 的时候通过–with-pcre= 的方式。

这里直接进行安装,相关依赖安装完成后,直接运行

ubuntu@VM-0-6-ubuntu:~/nginx-1.20.0$ ./configure

编译结果

ubuntu@VM-0-6-ubuntu:~/nginx-1.20.0$ make
ubuntu@VM-0-6-ubuntu:~/nginx-1.20.0$ sudo make install

安装结果

启动Nginx

ubuntu@VM-0-6-ubuntu:~/nginx-1.20.0$ sudo /usr/local/nginx/sbin/nginx

启动成功

Nginx启动参数

其中常用的就是 -t , -c , -p , -g , -s 这几个。
-c : 指定nginx 启动时使用的配置文件,默认为/usr/local/nginx/conf/nginx.conf ;
-t : 测试配置文件的语法是否正确;
-p : 指定nginx 服务器使用的文件的路径前缀,默认为/usr/local/nginx ;
-g : 通过命令行指定一些全局配置选项;
-s : 向nginx 进程发送信号。

停止Ngxin

  • -s stop: 快速关闭: nginx 强制停止服务, master 和worker 进程收到信号之后,会立即结束运行。
  • -s quit:
    1. 关闭监听端口,停止接收新的连接;
    2. Nginx 处理完当前的所有剩余请求;
    3. 停止Nginx 服务