企业级WEB服务Nginx安装

企业级WEB服务Nginx安装

1. Nginx版本和安装方式

  • Mainline version 主要开发版本,一般为奇数版本号,比如1.19
  • Stable version 当前最新稳定版,一般为偶数版本,如:1.20
  • Legacy versions 旧的稳定版,一般为偶数版本,如:1.18

Nginx安装可以使用yum或源码安装,但是推荐使用源码编译安装

  • yum的版本比较旧
  • 编译安装可以更方便自定义相关路径
  • 使用源码编译可以自定义相关功能,更方便业务的上的使用

2. 基于yum安装Nginx

2.1 查看当前系统中的Nginx版本

# Rocky Linux 9
[root@Rocky9 ~]# dnf info nginx
Last metadata expiration check: 2:51:40 ago on Fri 10 May 2024 12:57:53 PM CST.
Available Packages
Name         : nginx
Epoch        : 1
Version      : 1.20.1
Release      : 14.el9_2.1
Architecture : x86_64
Size         : 36 k
Source       : nginx-1.20.1-14.el9_2.1.src.rpm
Repository   : appstream
Summary      : A high performance web server and reverse proxy server
URL          : https://nginx.org
License      : BSD
Description  : Nginx is a web server and a reverse proxy server for HTTP, SMTP, POP3 and
             : IMAP protocols, with a strong focus on high concurrency, performance and low
             : memory usage.

[root@Rocky9 ~]#

# CentOS7 需提前配置好epel源
[root@localhost ~]#yum info nginx
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.tuna.tsinghua.edu.cn
 * epel: mirrors.tuna.tsinghua.edu.cn
 * extras: mirrors.tuna.tsinghua.edu.cn
 * updates: mirrors.aliyun.com
Available Packages
Name        : nginx
Arch        : x86_64
Epoch       : 1
Version     : 1.20.1
Release     : 10.el7
Size        : 588 k
Repo        : epel/7/x86_64
Summary     : A high performance web server and reverse proxy server
URL         : https://nginx.org
License     : BSD
Description : Nginx is a web server and a reverse proxy server for HTTP, SMTP, POP3 and
            : IMAP protocols, with a strong focus on high concurrency, performance and low
            : memory usage.

[root@localhost ~]#
# 我这里放到这里了
[epel]
name=epel
baseurl=https://mirrors.aliyun.com/epel/$releasever/$basearch/
        https://mirrors.cloud.tencent.com/epel/$releasever/$basearch/
        https://mirrors.tuna.tsinghua.edu.cn/epel/$releasever/$basearch/
gpgcheck=1
gpgkey=https://mirrors.tuna.tsinghua.edu.cn/epel/RPM-GPG-KEY-EPEL-7

可以看到这些都比较旧,查看官方版本

image-20240510155409672

2.2 官方包源安装最新版本 nginx

系统和EPEL源的中nignx版本较旧,可以安装官方源的最新版本

官方包链接:

https://nginx.org/en/linux_packages.html

官方yum源连接

https://nginx.org/en/linux_packages.html#RHEL

配置官方yum源

[root@Rocky9 ~]# vim /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

# yum列出所有版本
[root@Rocky9 ~]# yum list --showduplicates nginx
Last metadata expiration check: 0:01:25 ago on Fri 10 May 2024 04:07:30 PM CST.
Available Packages
nginx.x86_64                                               1:1.20.1-14.el9_2.1                                                appstream
nginx.x86_64                                               1:1.20.2-1.el9.ngx                                                 nginx-stable
nginx.x86_64                                               1:1.22.0-1.el9.ngx                                                 nginx-stable
nginx.x86_64                                               1:1.22.1-1.el9.ngx                                                 nginx-stable
nginx.x86_64                                               1:1.24.0-1.el9.ngx                                                 nginx-stable
nginx.x86_64                                               1:1.26.0-1.el9.ngx                                                 nginx-stable
[root@Rocky9 ~]#

#查看版本信息
[root@Rocky9 ~]# dnf info nginx
Last metadata expiration check: 0:15:08 ago on Fri 10 May 2024 04:07:30 PM CST.
Available Packages
Name         : nginx
Epoch        : 1
Version      : 1.26.0
Release      : 1.el9.ngx
Architecture : x86_64
Size         : 995 k
Source       : nginx-1.26.0-1.el9.ngx.src.rpm
Repository   : nginx-stable
Summary      : High performance web server
URL          : https://nginx.org/
License      : 2-clause BSD-like license
Description  : nginx [engine x] is an HTTP and reverse proxy server, as well as
             : a mail proxy server.

[root@Rocky9 ~]# dnf -y install nginx

2.3 检查安装

查看Nginx安装包信息

[root@Rocky9 ~]# rpm -q nginx
nginx-1.26.0-1.el9.ngx.x86_64
[root@Rocky9 ~]# rpm -qi nginx
Name        : nginx
Epoch       : 1
Version     : 1.26.0
Release     : 1.el9.ngx
Architecture: x86_64
Install Date: Fri 10 May 2024 04:24:28 PM CST
Group       : System Environment/Daemons
Size        : 3511437
License     : 2-clause BSD-like license
Signature   : RSA/SHA256, Wed 24 Apr 2024 03:09:17 AM CST, Key ID abf5bd827bd9bf62
Source RPM  : nginx-1.26.0-1.el9.ngx.src.rpm
Build Date  : Wed 24 Apr 2024 02:25:42 AM CST
Build Host  : ip-10-1-17-66.eu-central-1.compute.internal
Vendor      : NGINX Packaging <nginx-packaging@f5.com>
URL         : https://nginx.org/
Summary     : High performance web server
Description :
nginx [engine x] is an HTTP and reverse proxy server, as well as
a mail proxy server.
[root@Rocky9 ~]#

# 查看相关文件列表
[root@Rocky9 ~]# rpm -ql nginx
/etc/logrotate.d/nginx
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf
/etc/nginx/fastcgi_params
/etc/nginx/mime.types
/etc/nginx/modules
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/usr/lib/.build-id
/usr/lib/.build-id/52
/usr/lib/.build-id/52/145ff3b622c4ce68927371a3c1c03f2b74eebe
/usr/lib/.build-id/75
/usr/lib/.build-id/75/43f6f2a6666b01d673a74132d0fe256c90c306
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx
/usr/lib64/nginx/modules
/usr/libexec/initscripts/legacy-actions/nginx
/usr/libexec/initscripts/legacy-actions/nginx/check-reload
/usr/libexec/initscripts/legacy-actions/nginx/upgrade
/usr/sbin/nginx
/usr/sbin/nginx-debug
/usr/share/doc/nginx-1.26.0
/usr/share/doc/nginx-1.26.0/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
/var/cache/nginx
/var/log/nginx
[root@Rocky9 ~]#

# 查看版本
[root@Rocky9 ~]# nginx -v
nginx version: nginx/1.26.0
# 查看编译参数
[root@Rocky9 ~]# nginx -V
nginx version: nginx/1.26.0
built by gcc 11.3.1 20221121 (Red Hat 11.3.1-4) (GCC)
built with OpenSSL 3.0.7 1 Nov 2022
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-http_v3_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -flto=auto -ffat-lto-objects -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -fstack-protector-strong -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -march=x86-64-v2 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
[root@Rocky9 ~]#

2.4 nginx程序用法帮助

使用安装完成的二进制文件nginx

[root@Rocky9 ~]# nginx -h
nginx version: nginx/1.26.0
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
             [-e filename] [-c filename] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit	#显示版本
  -V            : show version and configure options then exit	# 显示编译参数
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing	# 静默模式
  -s signal     : send signal to a master process: stop, quit, reopen, reload	# 发送信号,reload信号会生成新的worker,但master不会重新生成
  -p prefix     : set prefix path (default: /etc/nginx/)	# 指定Nginx 目录
  -e filename   : set error log file (default: /var/log/nginx/error.log)	# 日志文件路径
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf) # 配置文件路径
  -g directives : set global directives out of configuration file # 设置全局指令,注意和配置文件不要同时配置,否则冲突

[root@Rocky9 ~]#

2.5 验证Nginx

# 检查nginx语法是否正确
[root@Rocky9 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@Rocky9 ~]#

2.6 Nginx启动文件

[root@Rocky9 ~]# cat /lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /var/run/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /var/run/nginx.pid)"

[Install]
WantedBy=multi-user.target
[root@Rocky9 ~]#

2.7 Nginx配置文件

[root@Rocky9 ~]# rpm -qc nginx
/etc/logrotate.d/nginx
/etc/nginx/conf.d/default.conf
/etc/nginx/fastcgi_params
/etc/nginx/mime.types
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
[root@Rocky9 ~]#

[root@Rocky9 ~]# tree /etc/nginx
/etc/nginx
├── conf.d
│   └── default.conf
├── fastcgi_params
├── mime.types
├── modules -> ../../usr/lib64/nginx/modules
├── nginx.conf
├── scgi_params
└── uwsgi_params

2 directories, 6 files
[root@Rocky9 ~]

[root@Rocky9 ~]# grep -Ev "^ *#|^$" /etc/nginx/nginx.conf
user  nginx;
worker_processes  auto;
error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;
    sendfile        on;
    keepalive_timeout  65;
    include /etc/nginx/conf.d/*.conf;
}
[root@Rocky9 ~]#

2.8 启动 Nginx

[root@Rocky9 ~]# systemctl enable --now nginx
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.

[root@Rocky9 ~]# systemctl status nginx
● nginx.service - nginx - high performance web server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: disabled)
     Active: active (running) since Fri 2024-05-10 16:41:59 CST; 13s ago
       Docs: http://nginx.org/en/docs/
    Process: 122073 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
   Main PID: 122074 (nginx)
      Tasks: 3 (limit: 10943)
     Memory: 3.1M
        CPU: 19ms
     CGroup: /system.slice/nginx.service
             ├─122074 "nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf"
             ├─122075 "nginx: worker process"
             └─122076 "nginx: worker process"

May 10 16:41:59 Rocky9.0 systemd[1]: Starting nginx - high performance web server...
May 10 16:41:59 Rocky9.0 systemd[1]: Started nginx - high performance web server.
[root@Rocky9 ~]# ps aux | grep nginx
root      122074  0.0  0.0  11316  1196 ?        Ss   16:41   0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx     122075  0.0  0.2  14744  5256 ?        S    16:41   0:00 nginx: worker process
nginx     122076  0.0  0.2  14744  5256 ?        S    16:41   0:00 nginx: worker process
root      122081  0.0  0.1   6408  2180 pts/0    S+   16:42   0:00 grep --color=auto nginx
[root@Rocky9 ~]#
[root@Rocky9 ~]# pstree -p | grep nginx
           |-nginx(122074)-+-nginx(122075)
           |               `-nginx(122076)
[root@Rocky9 ~]#

3. Nginx 编译安装

编译器介绍

**GCC(GNU Compiler Collection)**

  1. 全称与发展:GCC 最初代表 GNU C Compiler,因为它最初只用于编译 C 语言。随着时间的推移,GCC 增加了对其他编程语言的支持,包括 C++、Fortran、Pascal、Objective-C、Java 和 Ada 等,因此其名称改为 GNU Compiler Collection。
  2. 许可协议:GCC 是在 GNU General Public License (GPL) 和 GNU Lesser General Public License (LGPL) 下发布的。这些许可证允许用户自由地使用、修改和重新分发软件,只要他们也将修改后的软件以相同的许可协议发布。
  3. 平台兼容性:GCC 是多种 Unix-like 系统(包括 Linux 和 macOS)的标准编译器。GCC 通过不断扩展,支持了多种计算机架构和操作系统,使其成为开发跨平台软件的重要工具。

**源码安装的额外工具**

  1. Automake:这是一个用于生成 Makefile 的工具,它简化了编译过程中的管理任务。Automake 是 GNU 自动化工具链的一部分,与 Autoconf 和 Libtool 一起使用,可以自动处理许多编译和构建软件的复杂细节。

  2. 第三方库:编译一些软件(如 Nginx)时,可能需要依赖于特定的第三方库来支持额外的功能:

    • PCRE(Perl Compatible Regular Expressions):这是一个库,提供类似 Perl 的正则表达式功能,对于实现如 Nginx 中的重写规则非常重要。
    • zlib:提供压缩功能,对于支持如 gzip 压缩的 Nginx 模块是必需的。
    • OpenSSL:提供加密功能,对于实现 SSL/TLS 支持,例如在 Nginx 中配置 HTTPS,是必不可少的。

3.1 编译安装 Nginx

官方源码包下载地址:

https://nginx.org/en/download.html

编译安装

[root@Rocky9 ~]# yum -y install gcc pcre-devel openssl-devel zlib-devel
[root@Rocky9 ~]# useradd -s /sbin/nologin nginx
[root@Rocky9 ~]# cd /usr/local/src/
[root@Rocky9 ~]# wget https://nginx.org/download/nginx-1.24.0.tar.gz
[root@Rocky9 ~]# tar xf nginx-1.24.0.tar.gz
[root@Rocky9 ~]# cd nginx-1.24.0/

[root@Rocky9 nginx-1.24.0]#  ./configure --prefix=/apps/nginx \
  --user=nginx \
  --group=nginx \
  --with-http_ssl_module \
  --with-http_v2_module \
  --with-http_realip_module \
  --with-http_stub_status_module \
  --with-http_gzip_static_module \
  --with-pcre \
  --with-stream \
  --with-stream_ssl_module \
  --with-stream_realip_module

[root@Rocky9 nginx-1.24.0]# make && make install
[root@Rocky9 nginx-1.24.0]# chown -R nginx.nginx /apps/nginx

nginx完成安装以后,有四个主要的目录

[root@Rocky9 src]# ll /apps/nginx/
total 4
drwxr-xr-x 2 root  root  4096 May 10 16:39 conf
drwxr-xr-x 2 root  root    40 May  9 22:28 html
drwxr-xr-x 2 root  root    41 May  9 22:45 logs
drwxr-xr-x 2 root  root    36 May  9 22:44 sbin
[root@Rocky9 src]#
conf:保存nginx所有的配置文件,其中nginx.conf是nginx服务器的最核心最主要的配置文件,其他的.conf则是用来配置nginx相关的功能的,例如fastcgi功能使用的是fastcgi.conf和fastcgi_params两个文件,配置文件一般都有个样板配置文件,是文件名.default结尾,使用的使用将其复制为并将default去掉即可。
html目录中保存了nginx服务器的web文件,但是可以更改为其他目录保存web文件,另外还有一个50x的web文件是默认的错误页面提示页面。
logs:用来保存nginx服务器的访问日志错误日志等日志,logs目录可以放在其他路径,比如/var/logs/nginx里面。
sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。

3.2 验证版本和编译参数

[root@Rocky9 src]# ls /apps/nginx/sbin/
nginx
[root@Rocky9 src]#ln -s /apps/nginx/sbin/nginx /usr/sbin/
[root@Rocky9 src]# nginx -v
nginx version: nginx/1.24.0
[root@Rocky9 src]#
root@Rocky9 src]# nginx -V
nginx version: nginx/1.24.0
built by gcc 11.4.1 20230605 (Red Hat 11.4.1-2) (GCC)
built with OpenSSL 3.0.7 1 Nov 2022
TLS SNI support enabled
configure arguments: --prefix=/apps/nginx/ --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
[root@Rocky9 src]#

3.3 启动和停止 nginx 测试访问web界面

[root@Rocky9 src]# nginx
[root@Rocky9 src]# ps aux | grep nginx
root      126226  0.0  0.0   9868   928 ?        Ss   17:24   0:00 nginx: master process nginx
nginx     126227  0.0  0.2  13764  4660 ?        S    17:24   0:00 nginx: worker process
nginx     126228  0.0  0.2  13764  4660 ?        S    17:24   0:00 nginx: worker process
root      126230  0.0  0.1   6408  2188 pts/0    S+   17:24   0:00 grep --color=auto nginx
[root@Rocky9 src]#
[root@Rocky9 src]# ss -tln
State           Recv-Q          Send-Q                   Local Address:Port                   Peer Address:Port          Process
LISTEN          0               511                            0.0.0.0:80                          0.0.0.0:*
LISTEN          0               128                            0.0.0.0:22                          0.0.0.0:*
LISTEN          0               128                               [::]:22                             [::]:*
[root@Rocky9 src]#

# 关闭nginx
[root@Rocky9 src]# nginx -s stop

3.4 创建 Nginx 自启动文件

# 复制同一版本的nginx的yum安装生成的service文件
[root@Rocky9 src]# vim /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/apps/nginx/run/nginx.pid
ExecStart=/usr/sbin/nginx -c /apps/nginx/conf/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /apps/nginx/run/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /apps/nginx/run/nginx.pid)"

[Install]
WantedBy=multi-user.target

[root@Rocky9 src]# mkdir /apps/nginx/run/

#修改配置文件
[root@Rocky9 src]# vim /apps/nginx/conf/nginx.conf
pid /apps/nginx/run/nginx.pid;

3.5 验证 Nginx 自启动文件

[root@Rocky9 src]# systemctl daemon-reload
[root@Rocky9 src]# systemctl enable --now nginx

[root@Rocky9 src]# ll /apps/nginx/run/nginx.pid
-rw-r--r-- 1 root root 7 May 10 17:29 /apps/nginx/run/nginx.pid
[root@Rocky9 src]#
[root@Rocky9 src]# systemctl status nginx
● nginx.service - nginx - high performance web server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: disabled)
     Active: active (running) since Fri 2024-05-10 17:29:58 CST; 4min 15s ago
       Docs: http://nginx.org/en/docs/
    Process: 126436 ExecStart=/usr/sbin/nginx -c /apps/nginx/conf/nginx.conf (code=exited, status=0/SUCCESS)
   Main PID: 126437 (nginx)
      Tasks: 3 (limit: 10943)
     Memory: 2.7M
        CPU: 13ms
     CGroup: /system.slice/nginx.service
             ├─126437 "nginx: master process /usr/sbin/nginx -c /apps/nginx/conf/nginx.conf"
             ├─126438 "nginx: worker process"
             └─126439 "nginx: worker process"

May 10 17:29:58 Rocky9.0 systemd[1]: Starting nginx - high performance web server...
May 10 17:29:58 Rocky9.0 systemd[1]: Started nginx - high performance web server.
[root@Rocky9 src]# systemctl stop nginx
[root@Rocky9 src]# ss -tln
State           Recv-Q          Send-Q                   Local Address:Port                   Peer Address:Port          Process
LISTEN          0               128                            0.0.0.0:22                          0.0.0.0:*
LISTEN          0               128                               [::]:22                             [::]:*
[root@Rocky9 src]#

4. 自动化部署nginx

4.1 一键安装 nginx 脚本

#! /bin/bash
#-----------------------------------------------------
#Author:            XingYuyu
#Date:              2024-04-27
#Blog:              http://8.141.4.74
#Filename:          install_nginx.sh
#Description:       [编译安装nginx-1.26,适用于CentOS、Rocky、Ubuntu全系列版本]
#-----------------------------------------------------
SRC_DIR=/usr/local/src
NGINX_URL=https://nginx.org/download/
NGINX_FILE=nginx-1.26.0
TAR=.tar.gz
NGINX_INSTALL_DIR=/apps/nginx
CPUS=`lscpu | awk '/^CPU\(s\)/{print $2}'`

color(){
  RES_COL=60
  MOVE_TO_COL="echo -en \e[${RES_COL}G"
  SETCOLOR_SUCCESS="echo -en \e[1;32m"
  SETCOLOR_FAILURE="echo -en \e[1;31m"
  SETCOLOR_WARNING="echo -en \e[1;33m"
  SETCOLOR_NORMAL="echo -en \e[0m"
  echo -n "$1" && $MOVE_TO_COL
  echo -n "["
  if [ $2 = "success" -o $2 = "0" ];then
    ${SETCOLOR_SUCCESS}
    echo -n $"  OK  "
  elif [ $2 = "failure" -o $2 = "1" ];then
    ${SETCOLOR_FAILURE}
    echo -n $"FAILED"
  else
    ${SETCOLOR_WARNING}
    echo -n $"WARNING"
  fi
  ${SETCOLOR_NORMAL}
  echo -n $"]"
  echo
}

os_type(){
 awk -F'[ "]' '/^NAME/{print $2}' /etc/os-release
}

os_version(){
  awk -F'[ ."]' '/^VERSION=/{print $2}' /etc/os-release
}

check(){
  [ -e ${NGINX_INSTALL_DIR}  ] && { color "nginx 已安装,请卸载后再运行该脚本" 1;exit; }
  cd ${SRC_DIR}
  if [ -e ${NGINX_FILE}${TAR} ];then
    color "相关文件已准备好" 0
  else
    color "Start downloading nginx source code package" 0
    wget ${NGINX_URL}${NGINX_FILE}${TAR}
    [ $? -ne 0  ] && { color "下载 ${NGINX_FILE}${TAR} 文件失败" 1; exit; }
  fi
}

install(){
  color "Start installing nginx" 0
  if id nginx &> /dev/null; then
    color "Nginx user already exists" 0
  else
     useradd -s /sbin/nologin -r nginx
     color "Create nginx user" 0
  fi
  color "Start installing nginx dependency package" 0
  if [ `os_type` == "CentOS" -a `os_version` == '8' ];then
    yum -y -q install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed
  elif [ `os_type` == "CentOS" -a `os_version` == '7' ];then
    yum -y -q  install make gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
  elif [ `os_type` == "Rocky" -a `os_version` == '8'  ];then
   yum -y -q install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed
  elif [  `os_type` == "Rocky" -a `os_version` == '9' ];then
   yum -y -q install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed
   else
     apt update &> /dev/null
     apt -y install make gcc libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev &> /dev/null
  fi
  cd $SRC_DIR
  tar xf ${NGINX_FILE}${TAR}
  NGINX_DIR=`echo ${NGINX_FILE}${TAR} | sed -nr 's/^(.*[0-9]).*/\1/p'`
  cd $NGINX_DIR
  ./configure --prefix=${NGINX_INSTALL_DIR} \
  --user=nginx \
  --group=nginx \
  --with-http_ssl_module \
  --with-http_v2_module \
  --with-http_realip_module \
  --with-http_stub_status_module \
  --with-http_gzip_static_module \
  --with-pcre \
  --with-stream \
  --with-stream_ssl_module \
  --with-stream_realip_module
  make -j $CPUS && make install
  [ $? -eq 0 ] && color "nginx 编译安装成功" 0 || { color "nginx 编译安装失败,退出!" 1;exit; }
  echo "PATH=${NGINX_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/nginx.sh
  cat >/lib/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=/bin/rm -f ${NGINX_INSTALL_DIR}/logs/nginx.pid
# 在启动命令之前执行的命令。1.删除PID文件,避免启动时出现文件残留问题; 2.通过-t选项检查Nginx配置的正确性。
ExecStartPre=${NGINX_INSTALL_DIR}/sbin/nginx -t
ExecStart=${NGINX_INSTALL_DIR}/sbin/nginx
# 定义如何重新加载Nginx,这里通过发送HUB信号到主进程ID。SIGHUB:这个信号用来通知一个运行中的进程重新加载其配置文件,在写入 systemd service 文件时使用 \ 来转义 $ 的原因是为了防止在处理 shell 脚本时对变量进行过早的展开。使用反斜杠 (\) 是一种在文本输入时保持变量原样不被解释的方法,特别是在涉及到像 systemd 这样的处理系统时,这个系统可能会读取这些变量并按照自己的方式解释它们。
# 在一个 shell 脚本中使用类似的语句创建或修改了 systemd 的服务文件,并在那个脚本中使用了 \ 来确保变量 $MAINPID 在文字层面上正确写入文件,而不是被 shell 解释为当前环境的一个变量值(通常是空的,因为 $MAINPID 在大多数 shell 环境中不会有预设值)。
#当你查看 service 文件时发现反斜杠 \ 消失了,这表明当脚本执行并实际写入到 service 文件中时,\ 完成了它的任务——防止变量被展开,所以在最终的文件中你只看到了 $MAINPID 而不是 \。这正是预期的结果,因为 service 文件需要保留未展开的变量,以便 systemd 在处理 service 时能够正确解析和使用这些变量。
# 经过验证,如果不加反斜杠生成的配置文件就变成了这样:ExecReload=/bin/kill -s HUP
# 在systemd服务单元文件中,ExecStartPost= 指令指定了在主服务(由 ExecStart= 指令启动)启动之后应该执行的命令。
ExecStartPost=/bin/sleep 2
ExecReload=/bin/kill -s HUP \$MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
  systemctl daemon-reload
  systemctl enable --now nginx &> /dev/null
  systemctl is-active nginx &> /dev/null || { color "nginx 启动失败,退出" 1;exit; }
  color "nginx 安装完成" 0

}
check
install
说明:安装nginx其它版本,只需要修改下面这个变量即可:
NGINX_FILE=nginx-1.26.0

增加了openssl和echo-nginx-module模块

#! /bin/bash
#-----------------------------------------------------
#Author:            XingYuyu
#Date:              2024-05-10
#Blog:              http://8.141.4.74
#Filename:          install_nginx.sh
#Description:       [编译安装nginx 1.26,适用于CentOS、Rocky、Ubuntu]
#-----------------------------------------------------
SRC_DIR=/usr/local/src
NGINX_URL=https://nginx.org/download/
NGINX_FILE=nginx-1.26.0
TAR=.tar.gz
ECHO_NGINX_FILE=echo-nginx-module-0.63
OPENSSL_FILE=openssl-3.3.0
NGINX_INSTALL_DIR=/apps/nginx
CPUS=`lscpu | awk '/^CPU\(s\)/{print $2}'`

color(){
  RES_COL=80
  MOVE_TO_COL="echo -en \e[${RES_COL}G"
  SETCOLOR_SUCCESS="echo -en \e[1;32m"
  SETCOLOR_FAILURE="echo -en \e[1;31m"
  SETCOLOR_WARNING="echo -en \e[1;33m"
  SETCOLOR_NORMAL="echo -en \e[0m"
  echo -n "$1" && $MOVE_TO_COL
  echo -n "["
  if [ $2 = "success" -o $2 = "0" ];then
    ${SETCOLOR_SUCCESS}
    echo -n $"  OK  "
  elif [ $2 = "failure" -o $2 = "1" ];then
    ${SETCOLOR_FAILURE}
    echo -n $"FAILED"
  else
    ${SETCOLOR_WARNING}
    echo -n $"WARNING"
  fi
  ${SETCOLOR_NORMAL}
  echo -n $"]"
  echo
}

os_type(){
 awk -F'[ "]' '/^NAME/{print $2}' /etc/os-release
}

os_version(){
  awk -F'[ ."]' '/^VERSION=/{print $2}' /etc/os-release
}

check(){
  [ -e ${NGINX_INSTALL_DIR}  ] && { color "nginx 已安装,请卸载后再运行该脚本" 1;exit; }
  cd ${SRC_DIR}
  if [ -e ${NGINX_FILE}${TAR}  ];then
    color "${NGINX_FILE}已经准备完成!" 0
    if [ -e ${ECHO_NGINX_FILE}${TAR} ] && [ -e ${OPENSSL_FILE}${TAR} ];then
     color "${ECHO_NGINX_FILE}${OPENSSL_FILE}安装包准备完成!" 0
    else
      { color "请上传echo-nginx-module和openssl安装包到${SRC_DIR}下" 1;exit; }
    fi
  elif [ -e ${ECHO_NGINX_FILE}${TAR} ] && [ -e ${OPENSSL_FILE}${TAR} ];then
    color "${ECHO_NGINX_FILE}${OPENSSL_FILE}安装包准备完成!" 0
    color "缺失${NGINX_FILE}安装包,开始安装" 0
    wget ${NGINX_URL}${NGINX_FILE}${TAR}
    [ $? -ne 0  ] && { color "下载 ${NGINX_FILE}${TAR} 文件失败" 1; exit; }
  else
    { color "请先上传echo-nginx-module和openssl安装包到${SRC_DIR}下" 1;exit; }
  fi
}

install(){
  color "Start installing nginx" 0
  if id nginx &> /dev/null; then
    color "Nginx user already exists" 0
  else
     useradd -s /sbin/nologin -r nginx
     color "Create nginx user" 0
  fi
  color "Start installing nginx dependency package" 0
  if [ `os_type` == "CentOS" -a `os_version` == '8' ];then
    yum -y -q install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed perl
  elif [ `os_type` == "CentOS" -a `os_version` == '7' ];then
    yum -y -q  install make gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed perl-IPC-Cmd
  elif [ `os_type` == "Rocky" -a `os_version` == '8'  ];then
   yum -y -q install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed perl-ExtUtils-Embed perl
  elif [  `os_type` == "Rocky" -a `os_version` == '9' ];then
   yum -y -q install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed perl-ExtUtils-Embed perl
   else
     apt update &> /dev/null
     apt -y install make gcc libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev libipc-cmd-perl &> /dev/null
  fi
  cd $SRC_DIR
  tar xf ${NGINX_FILE}${TAR}
  tar xf ${ECHO_NGINX_FILE}${TAR}
  tar xf ${OPENSSL_FILE}${TAR}
  NGINX_DIR=`echo ${NGINX_FILE}${TAR} | sed -nr 's/^(.*[0-9]).*/\1/p'`
  cd $NGINX_DIR
  ./configure --prefix=${NGINX_INSTALL_DIR} \
  --user=nginx \
  --group=nginx \
  --with-http_ssl_module \
  --with-http_v2_module \
  --with-http_realip_module \
  --with-http_stub_status_module \
  --with-http_gzip_static_module \
  --with-pcre \
  --with-stream \
  --with-stream_ssl_module \
  --with-stream_realip_module \
  --with-file-aio \
  --add-module=${SRC_DIR}/${ECHO_NGINX_FILE} \
  --with-openssl=${SRC_DIR}/${OPENSSL_FILE}
  make -j $CPUS && make install
  [ $? -eq 0 ] && color "nginx 编译安装成功" 0 || { color "nginx 编译安装失败,退出!" 1;exit; }
  echo "PATH=${NGINX_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/nginx.sh
  cat >/lib/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=/bin/rm -f ${NGINX_INSTALL_DIR}/logs/nginx.pid
# 在启动命令之前执行的命令。1.删除PID文件,避免启动时出现文件残留问题; 2.通过-t选项检查Nginx配置的正确性。
ExecStartPre=${NGINX_INSTALL_DIR}/sbin/nginx -t
ExecStart=${NGINX_INSTALL_DIR}/sbin/nginx
# 定义如何重新加载Nginx,这里通过发送HUB信号到主进程ID。SIGHUB:这个信号用来通知一个运行中的进程重新加载其配置文件,在写入 systemd service 文件时使用 \ 来转义 $ 的原因是为了防止在处理 shell 脚本时对变量进行过早的展开。使用反斜杠 (\) 是一种在文本输入时保持变量原样不被解释的方法,特别是在涉及到像 systemd 这样的处理系统时,这个系统可能会读取这些变量并按照自己的方式解释它们。
# 在一个 shell 脚本中使用类似的语句创建或修改了 systemd 的服务文件,并在那个脚本中使用了 \ 来确保变量 $MAINPID 在文字层面上正确写入文件,而不是被 shell 解释为当前环境的一个变量值(通常是空的,因为 $MAINPID 在大多数 shell 环境中不会有预设值)。
#当你查看 service 文件时发现反斜杠 \ 消失了,这表明当脚本执行并实际写入到 service 文件中时,\ 完成了它的任务——防止变量被展开,所以在最终的文件中你只看到了 $MAINPID 而不是 \。这正是预期的结果,因为 service 文件需要保留未展开的变量,以便 systemd 在处理 service 时能够正确解析和使用这些变量。
# 经过验证,如果不加反斜杠生成的配置文件就变成了这样:ExecReload=/bin/kill -s HUP
# 在systemd服务单元文件中,ExecStartPost= 指令指定了在主服务(由 ExecStart= 指令启动)启动之后应该执行的命令。
ExecStartPost=/bin/sleep 2
ExecReload=/bin/kill -s HUP \$MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
  systemctl daemon-reload
  systemctl enable --now nginx &> /dev/null
  systemctl is-active nginx &> /dev/null || { color "nginx 启动失败,退出" 1;exit; }
  color "nginx 安装完成" 0

}
check
install

4.2 利用 ansible 安装nginx

---
- hosts: webservers
  remote_user: root
  gather_facts: yes
  vars:
    nginx_version: nginx-1.24.0
    suffix: .tar.gz
    download_dir: /usr/local/src/
    install_dir: /apps/nginx/
    user: nginx
    group: nginx

  tasks:
    - name: install packages on Rocky8/CentOS8/Rocky9
      yum:
        name:
          - gcc
          - make
          - pcre-devel
          - openssl-devel
          - zlib-devel
        state: present
      when: > 
        (ansible_facts['distribution'] == "Rocky" and ansible_facts['distribution_major_version'] == "8") or
        (ansible_facts['distribution'] == "Rocky" and ansible_facts['distribution_major_version'] == "9") or
        (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "8")
    - name: install packages on centos7
      yum:
        name:
          - gcc
          - make
          - pcre-devel
          - openssl-devel
          - zlib-devel
        state: present
      when:
        - ansible_facts['distribution'] == "CentOS"
        - ansible_facts['distribution_major_version'] == "7"
    - name: install packages on ubuntu
      apt:
        name:
          - gcc
          - make
          - libpcre3
          - libpcre3-dev
          - openssl
          - libssl-dev
          - zlib1g-dev
        state: present
      when:
        - ansible_facts['distribution'] == "Ubuntu"
    - name: group "{{ group }}"
      group: name={{ group }}  state=present system=yes
    - name: user "{{ user }}"
      user:
        name: "{{ user }}"
        shell: /sbin/nologin
        system: yes
        group: "{{ group }}"
        home: "/home/{{ user }}"
        create_home: no
    - name: unarchive
      unarchive:
        src: "https://nginx.org/download/{{ nginx_version }}{{ suffix }}"
        dest: "{{ download_dir }}"
        remote_src: yes
    - name: configure
      shell: >
        ./configure
        --prefix={{ install_dir }} \
        --user=nginx \
        --group=nginx \
        --with-http_ssl_module \
        --with-http_v2_module \
        --with-http_realip_module \
        --with-http_stub_status_module \
        --with-http_gzip_static_module \
        --with-pcre \
        --with-stream \
        --with-stream_ssl_module \
        --with-stream_realip_module 
      args:
        chdir: "{{ download_dir }}{{ nginx_version }}/"
    - name: make
      shell: make -j "{{ ansible_processor_vcpus }}" && make install
      args:
        chdir: "{{ download_dir }}{{ nginx_version }}/"
    - name: link
      file:
        src: "{{ install_dir }}sbin/nginx"
        dest: /usr/sbin/nginx
        state: link
    - name: service file
      copy:
        content: |
          [Unit]
          Description=nginx - high performance web server
          Documentation=http://nginx.org/en/docs/
          After=network-online.target remote-fs.target nss-lookup.target
          Wants=network-online.target
          
          [Service]
          Type=forking
          PIDFile={{ install_dir }}run/nginx.pid
          ExecStart=/usr/sbin/nginx -c {{ install_dir }}conf/nginx.conf
          ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat {{ install_dir }}run/nginx.pid)"
          ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat {{ install_dir }}run/nginx.pid)"
          
          [Install]
          WantedBy=multi-user.target
        dest: /lib/systemd/system/nginx.service
    - name: change configure pid location and change worker_processes
      lineinfile:
        path: "{{ item.path }}"
        regexp: "{{ item.regexp }}"
        line: "{{ item.line }}"
      with_items:
        - { path: "{{ install_dir }}conf/nginx.conf",regexp: '^worker_processes',line: "worker_processes {{ ansible_processor_vcpus }};" }
        - { path: "{{ install_dir }}conf/nginx.conf",regexp: '^#pid',line: 'pid         run/nginx.pid;' }
    - name: create dir run and modify directory permission
      file:
        path: "{{ install_dir }}run"
        owner: "{{ user }}"
        group: "{{ group }}"
        state: directory
    - name: start service
      service:
        name: nginx
        state: started
        enabled: yes
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XingYuyu_Coder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值