Linux内核之外的运维宇宙
Linux运维实战笔记:从系统架构到自动化运维

nginx安装使用文档--保姆级

1. 创建用户和用户组

groupadd nginx
useradd -r -g nginx -s /sbin/nologin nginx
  • groupadd nginx:创建一个名为 nginx 的用户组。
  • useradd -r -g nginx -s /sbin/nologin nginx:创建一个名为 nginx 的系统用户,并将其归属于 nginx 用户组。-r 表示这是一个系统账户,-g nginx 指定该用户属于 nginx 用户组,-s /sbin/nologin 则指定该用户无法登录系统。

2. 创建安装目录并设置权限

mkdir -p /soft/nginx
chown -R nginx:nginx /soft/nginx
  • mkdir -p /soft/nginx:创建 /soft/nginx 目录,用于存放 Nginx 的安装文件。
  • chown -R nginx:nginx nginx:将 /soft/nginx 目录的所有权赋给 nginx 用户和 nginx 用户组,确保 Nginx 用户可以访问和操作这些文件。

3. 解压 Nginx 安装包

tar -zxvf nginx-1.27.3.tar.gz
  • tar -zxvf nginx-1.27.3.tar.gz:解压 Nginx 安装包 nginx-1.27.3.tar.gz,使得安装文件可以被访问并进行编译。

4. 安装依赖软件包

yum install -y gcc gcc-c++ make pcre pcre-devel openssl openssl-devel libxml2-devel libxslt-devel gd-devel
  • yum install -y:通过 yum 包管理工具自动安装一系列必要的开发工具和库。
    • gccgcc-c++:C 和 C++ 编译器,用于编译 Nginx 源码。
    • make:构建工具,帮助编译源代码。
    • pcrepcre-devel:正则表达式库和开发文件,是 Nginx 的核心模块依赖之一。
    • opensslopenssl-devel:用于支持 SSL/TLS 加密。
    • libxml2-devellibxslt-develgd-devel:其他支持模块所需的开发库,涉及 XML 解析、XSLT 和图像处理。

5. 配置 Nginx 编译选项

cd nginx-1.27.3
./configure --prefix=/soft/nginx \
            --user=nginx \
            --group=nginx \
            --with-http_ssl_module \
            --with-file-aio \
            --with-http_v2_module \
            --with-http_realip_module \
            --with-http_addition_module \
            --with-http_xslt_module \
            --with-http_image_filter_module=dynamic \
            --with-http_sub_module \
            --with-http_dav_module \
            --with-http_flv_module \
            --with-http_mp4_module \
            --with-http_gunzip_module \
            --with-http_gzip_static_module \
            --with-http_random_index_module \
            --with-http_secure_link_module \
            --with-http_degradation_module \
            --with-http_slice_module \
            --with-mail=dynamic \
            --with-mail_ssl_module \
            --with-pcre \
            --with-pcre-jit \
            --with-stream \
            --with-stream_ssl_module \
            --with-debug \
            --with-compat
  • cd nginx-1.27.3:进入 Nginx 解压后的目录。
  • ./configure:执行 configure 脚本来配置编译选项。下面是几个常见选项的解释:
    • --prefix=/soft/nginx:指定 Nginx 安装目录为 /soft/nginx
    • --user=nginx --group=nginx:指定 Nginx 运行时的用户和用户组。
    • --with-http_ssl_module:启用 HTTPS 支持模块。
    • --with-file-aio:启用异步文件操作。
    • --with-http_v2_module:启用 HTTP/2 支持。
    • --with-pcre:启用 PCRE(正则表达式)库支持。
    • --with-debug:启用调试模式。
    • --with-compat:启用与其他 Nginx 模块的兼容性。
    • 其余模块如 --with-http_realip_module--with-mail_ssl_module 等,都是启用不同的功能模块,如防火墙、图片处理、邮件代理等。

6. 编译和安装 Nginx

make & make install
  • make:开始编译 Nginx 源码,生成可执行文件。
  • make install:将编译后的文件安装到指定目录(即 /soft/nginx)。

7. 设置文件权限

cd /soft/nginx
chown -R nginx:nginx *
  • chown -R nginx:nginx *:递归地将 /soft/nginx 目录下的所有文件和子目录的所有权设置为 nginx 用户和 nginx 用户组,确保 Nginx 用户可以访问和操作安装文件。

8.修改nginx配置文件

 user nginx nginx;

 端口改为8088  (非root用户启动不能使用80)

若非要使用80端口,则使用下述方式:

setcap cap_net_bind_service=+ep /soft/nginx/sbin/nginx
getcap /soft/nginx/sbin/nginx
  • setcap:是一个 Linux 命令,用于设置文件的 能力(capabilities),即赋予文件特定的权限,而不需要给予该文件完全的超级用户(root)权限。
  • cap_net_bind_service=+ep:该能力允许 nginx 进程绑定到低端口(<1024)的端口,比如 HTTP 的 80 端口和 HTTPS 的 443 端口。
    • +ep:表示添加(+cap_net_bind_service 权限,并使其生效(ep 代表 "effective" 和 "permitted" 权限)。
  • getcap:用于查看文件的当前能力(capabilities)。执行此命令后,它会显示出 nginx 可执行文件的能力

为什么要使用 setcap 命令?

通常,只有 root 用户才能绑定到端口 1024 以下的端口(如 80 和 443)。通过 setcap 命令,普通用户(如 nginx 用户)可以在不拥有 root 权限的情况下绑定这些低端口。这种方式更安全,因为它只授予所需的权限,而不是将整个进程提升为 root 用户。

执行该命令后,输出会类似于:

/soft/nginx/sbin/nginx = cap_net_bind_service+ep

如果 setcap 命令成功执行并赋予了文件所需的能力,那么你将看到类似上面的输出,确认 nginx 进程具备了绑定低端口(<1024)的能力。

9. 创建 systemd 服务文件

vi /etc/systemd/system/nginx.service

创建或编辑 /etc/systemd/system/nginx.service 文件,通过 systemd 启动和管理 Nginx 服务。

[Unit]
Description=The Nginx HTTP and reverse proxy server
After=network.target
[Service]
Type=forking
PIDFile=/soft/nginx/logs/nginx.pid
ExecStartPre=/soft/nginx/sbin/nginx -t
ExecStart=/soft/nginx/sbin/nginx
ExecReload=/soft/nginx/sbin/nginx -s reload
ExecStop=/soft/nginx/sbin/nginx -s stop
AmbientCapabilities=CAP_NET_BIND_SERVICE
PrivateTmp=true
User=nginx
Group=nginx
[Install]
WantedBy=multi-user.target
  • [Unit] 部分是服务的描述信息。

    • Description:描述该服务为 Nginx HTTP 和反向代理服务器。
    • After=network.target:指定该服务应该在网络配置完成后启动(即依赖网络)。
  • [Service] 部分是关于服务如何运行的配置。

    • Type=forking:表明 Nginx 在启动时会生成一个子进程,并在后台运行。
    • PIDFile=/soft/nginx/logs/nginx.pid:指定存储 Nginx 进程 ID 的文件。
    • ExecStartPre=/soft/nginx/sbin/nginx -t:在启动 Nginx 之前先运行 nginx -t,用于测试 Nginx 配置文件的正确性。
    • ExecStart=/soft/nginx/sbin/nginx:启动 Nginx 服务的命令。
    • ExecReload=/soft/nginx/sbin/nginx -s reload:重新加载 Nginx 配置的命令。
    • ExecStop=/soft/nginx/sbin/nginx -s stop:停止 Nginx 服务的命令。
    • AmbientCapabilities=CAP_NET_BIND_SERVICE:允许 Nginx 使用低端口(如 80 和 443)。
    • PrivateTmp=true:为服务提供一个私有的临时目录,确保服务的临时文件不会与其他服务共享。
    • User=nginxGroup=nginx:指定 Nginx 运行时使用的用户和组。
  • [Install] 部分配置了服务的启动目标。

    • WantedBy=multi-user.target:使得服务在多用户目标(即默认运行级别)下自动启动。

10. 重新加载 systemd 配置并启动 Nginx

systemctl daemon-reload
systemctl start nginx
systemctl enable nginx
systemctl status nginx
  • systemctl daemon-reload:重新加载 systemd 配置文件,确保系统识别到新创建的 Nginx 服务文件。
  • systemctl start nginx:启动 Nginx 服务。
  • systemctl enable nginx:设置 Nginx 服务开机自动启动。
  • systemctl status nginx:查看 Nginx 服务的状态,确认服务是否启动成功。

11. 配置环境变量

vi ~/.bash_profile
export PATH=$PATH:/soft/nginx/sbin

source ~/.bash_profile
  • vi ~/.bash_profile:打开当前用户的 .bash_profile 文件,这是用户登录时执行的配置文件,可以设置环境变量。
  • export PATH=$PATH:/soft/nginx/sbin:将 /soft/nginx/sbin 添加到 PATH 环境变量中,这样就可以在任何地方直接使用 nginx 命令。
  • source ~/.bash_profile:使配置生效,更新当前 shell 的环境变量。

在 /etc/security/limits.conf 中添加以下两行配置:

* soft nofile 65535
* hard nofile 65535

为什么需要设置这些值?
(1) 解决资源限制问题

如果未配置或配置过低,可能导致以下问题:
    应用程序(如 Web 服务器、数据库)因无法打开足够多的文件而崩溃。
    高并发场景下,连接数受限(例如 Nginx、MySQL 需要处理大量客户端连接)。
    系统性能下降或报错(如 Too many open files)。

(2) 适配高负载场景

在服务器上运行需要处理大量文件或连接的应用时(如 Kafka、Hadoop、Redis),默认的 nofile 值(通常为 1024 或 4096)可能无法满足需求。
通过调整 soft 和 hard 值,可以提升系统的并发能力。

12.nginx主配置文件模板

user nginx nginx;

worker_processes auto;  # 根据可用的 CPU 核心数量自动调整
error_log logs/error.log warn;  # 设置更高的日志级别

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  10240;
}


http {

    include /soft/nginx/conf.d/*.conf;

    server_tokens off;  # 禁用所有 server 的版本信息
    client_body_timeout 60s;  # 设置全局请求体超时时间为60秒
    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;  # 开启高效文件传输
    tcp_nopush          on;  # 提高传输效率
    tcp_nodelay         on;  # 减少延迟
    keepalive_timeout   65;  # 连接保持活跃超时时间
    keepalive_requests 100;  # 每个连接允许的请求数
    types_hash_max_size 4096;
    resolver_timeout 30s;  # 设置 DNS 解析超时为 30 秒

    #开启 Gzip 压缩
    gzip on;
    gzip_types text/plain application/x-javascript text/css application/json application/xml;
    gzip_min_length 1000;  # 只有大于1000字节的文件才会压缩
    gzip_vary on;          # 根据请求的 Accept-Encoding 头来启用 Gzip


    server {
        listen       8088;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            fastcgi_intercept_errors on;  # 拦截 FastCGI 错误并由 Nginx 处理

        }

        # 定义错误页面
        error_page 404 /404.html;
        location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }

    }

    # HTTPS server

    #server {
    #   listen       4431 ssl;
    #    server_name  localhost;

    #    ssl_certificate      /soft/nginx/star_dpca_com_cn.pem;
    #    ssl_certificate_key  /soft/nginx/star_dpca_com_cn.key;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


#}
}

13.nginx配置文件通用模板

模板一:

server {
    listen 9091;
    server_name your_domian;

    location / {
        proxy_pass http://your_ip;
        client_max_body_size 100M;  # 允许最大请求体为100M

        # Set headers
        proxy_set_header Host IP:9091;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # Manage Cookies
        proxy_set_header Cookie $http_cookie;
        proxy_cookie_path / /;

        # CORS headers
        add_header 'Access-Control-Allow-Origin' '*';  # 这里根据需要设置为特定域名
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE,HEAD';  # 增加PUT和DELETE方法
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With';
        add_header 'Access-Control-Allow-Credentials' 'true';  # 如果需要支持带cookie的请求
        add_header 'Access-Control-Max-Age' 86400;  # 预检请求的缓存时间

        # Timeout settings
        proxy_read_timeout 90;
        proxy_connect_timeout 90;
        proxy_send_timeout 90;

        # Optional logging
        access_log /var/log/nginx/dd_access.log;
        error_log /var/log/nginx/dd_error.log;
    }

}

模板二:

server {
    listen 9098;
    server_name your_domian;

    location / {
        # HTTP代理请求
        proxy_pass http://IP:3000;
        client_max_body_size 200M;

        # WebSocket代理设置
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;         # 必须设置Upgrade头以支持WebSocket
        proxy_set_header Connection 'upgrade';          # 必须保持Connection为upgrade
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

        # 管理Cookies
        proxy_set_header Cookie $http_cookie;
        proxy_cookie_path / /;

        # CORS 相关头部
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, HEAD';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Max-Age' 86400;

        # 设置超时
        proxy_read_timeout 90;
        proxy_connect_timeout 90;
        proxy_send_timeout 90;

        # Optional logging
        access_log /var/log/nginx/AI3_access.log;
        error_log /var/log/nginx/AI3_error.log;
    }

    # 特别针对WebSocket路径配置
    location /queue/ {
        proxy_pass http://IP:3000;    # 假设你的 WebSocket 服务在这个端口
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;  # 必须设置 Upgrade 请求头
        proxy_set_header Connection 'upgrade';   # 必须保持连接为 upgrade
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

        # 超时设置
        proxy_read_timeout 90;
        proxy_connect_timeout 90;
        proxy_send_timeout 90;

        # 可选的日志
        access_log /var/log/nginx/websocket2_access.log;
        error_log /var/log/nginx/websocket2_error.log;
    }
}

模板三:

stream {
    upstream db_servers {
        server IP:端口;
        least_conn;
    }

    server {
        listen 端口;

        # 只允许特定IP访问
        allow ~IP~;
        allow ~IP~;
        deny all;  # 拒绝其他所有IP

        proxy_pass db_servers;

        proxy_timeout 120s;
        proxy_connect_timeout 300s;

        error_log  /soft/nginx/logs/db_proxy_error.log;
    }
}

拦截特定路径配置

    # 拦截特定路径
    location = /bpm/sealimage.zz {
        return 403;  # 返回 403 Forbidden
        # 或者使用 return 404; 返回 404 Not Found
    }
posted on 2025-05-22 14:59  一叶舟-小刀哥  阅读(103)  评论(0)    收藏  举报