核心内容摘要
黑土腿法:足尖上的艺术,技艺的传承
前言Nginx作为高性能的HTTP和反向代理服务器在现代Web架构中扮演着核心角色。
本文将提供包管理器安装、源码编译安装、Docker部署三种主流安装方案涵盖虚拟主机配置、SSL证书部署、负载均衡设置等生产环境必备技能助你快速搭建稳定高效的Web服务器环境。
安装前准备与方案选择方案对比表安装方法 优点 缺点 适用场景包管理器 简单快捷自动管理依赖 版本可能较旧 快速部署生产环境源码编译 最新版本高度可定制 步骤复杂需手动更新 开发测试特定需求Docker 环境隔离快速部署 性能略有损耗 容器化微服务架构环境检查bash检查系统信息cat /etc/os-releaseuname -m # 确认架构x86_64/arm64检查端口占用80/443sudo netstat -tulnp | grep -E ‘:(80|
’或sudo ss -tulnp | grep -E ‘:(80|
’检查防火墙状态sudo ufw status # Ubuntusudo firewall-cmd --state # CentOS
方法一包管理器安装推荐新手Ubuntu/Debian 安装最新稳定版bash更新包列表sudo apt updatesudo apt upgrade -y安装依赖sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring -y导入Nginx官方签名密钥curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg /dev/null添加Nginx稳定版仓库echo “deb [signed-by/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu $(lsb_release -cs) nginx” | sudo tee /etc/apt/sources.list.d/nginx.list安装Nginxsudo apt updatesudo apt install nginx -y验证安装nginx -v输出nginx version: nginx/
1.
2
0CentOS/RHEL 安装bashCentOS 8/RHEL 8sudo dnf install epel-release -ysudo dnf install nginx -y或使用Nginx官方仓库最新版本cat /etc/yum.repos.d/nginx.repo EOF[nginx-stable]namenginx stable repobaseurlhttp://nginx.org/packages/centos/$releasever/$basearch/gpgcheck1enabled1gpgkeyhttps://nginx.org/keys/nginx_signing.keymodule_hotfixestrueEOFsudo dnf install nginx -y
基础服务管理bash启动Nginxsudo systemctl start nginx设置开机自启sudo systemctl enable nginx查看状态sudo systemctl status nginx重启服务sudo systemctl restart nginx重新加载配置不中断服务sudo systemctl reload nginx停止服务sudo systemctl stop nginx
方法二源码编译安装最新特性安装编译依赖bashUbuntu/Debiansudo apt install build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev -yCentOS/RHELsudo yum install gcc make pcre-devel zlib-devel openssl-devel -y
下载与解压源码bash创建安装目录sudo mkdir -p /opt/nginxcd /opt/nginx下载最新稳定版查看官网获取最新版本号wget https://nginx.org/download/nginx-
1.
24.
tar.gztar -zxvf nginx-
1.
24.
tar.gzcd nginx-
1.
24.
配置编译选项bash查看所有配置选项./configure --help常用配置示例./configure–prefix/usr/local/nginx–sbin-path/usr/sbin/nginx–conf-path/etc/nginx/nginx.conf–pid-path/var/run/nginx.pid–http-log-path/var/log/nginx/access.log–error-log-path/var/log/nginx/error.log–with-http_ssl_module–with-http_v2_module–with-http_realip_module–with-http_gzip_static_module–with-http_stub_status_module–with-threads–with-file-aio–with-pcre配置成功输出Configuration summary using system PCRE library using system OpenSSL library…nginx path prefix: “/usr/local/nginx”编译与安装bash编译使用所有CPU核心加速make -j$(nproc)安装sudo make install创建软链接sudo ln -s /usr/local/nginx/sbin/nginx /usr/sbin/nginx
创建Systemd服务bash创建服务文件sudo nano /etc/systemd/system/nginx.service添加以下内容ini[Unit]Descriptionnginx - high performance web serverDocumentationhttps://nginx.org/en/docs/Afternetwork.target remote-fs.target nss-lookup.target[Service]TypeforkingPIDFile/var/run/nginx.pidExecStartPre/usr/sbin/nginx -t -c /etc/nginx/nginx.confExecStart/usr/sbin/nginx -c /etc/nginx/nginx.confExecReload/bin/kill -s HUP $MAINPIDExecStop/bin/kill -s TERM $MAINPIDPrivateTmptrue[Install]WantedBymulti-user.targetbash重载systemd并启动服务sudo systemctl daemon-reloadsudo systemctl start nginxsudo systemctl enable nginx
方法三Docker快速部署安装Docker如未安装bashUbuntu/Debiansudo apt install docker.io docker-compose -ysudo systemctl start dockersudo systemctl enable docker添加用户到docker组避免每次sudosudo usermod -aG docker $USERnewgrp docker
拉取并运行Nginxbash拉取官方镜像docker pull nginx:alpine # 轻量版或docker pull nginx:latest # 完整版运行临时容器测试docker run --name nginx-test -p 80:80 -d nginx:alpine访问测试curl http://localhost
持久化配置与数据bash创建本地目录mkdir -p ~/nginx-docker/{conf,html,logs,certs}复制默认配置docker run --name nginx-temp -d nginx:alpinedocker cp nginx-temp:/etc/nginx/nginx.conf ~/nginx-docker/conf/docker cp nginx-temp:/etc/nginx/conf.d ~/nginx-docker/docker stop nginx-temp docker rm nginx-temp创建自定义配置文件cat ~/nginx-docker/conf.d/default.conf ‘EOF’server {listen 80;server_name localhost;location / { root /usr/share/nginx/html; index index.html; }}EOF创建测试页面echo “Nginx Docker Test” ~/nginx-docker/html/index.html
使用Docker Compose部署yamldocker-compose.ymlversion: ‘
8’services:nginx:image: nginx:alpinecontainer_name: nginx-webports:- “80:80”- “443:443”volumes:- ./conf/nginx.conf:/etc/nginx/nginx.conf- ./conf.d:/etc/nginx/conf.d- ./html:/usr/share/nginx/html- ./logs:/var/log/nginx- ./certs:/etc/nginx/certsrestart: unless-stoppednetworks:- web-networknetworks:web-network:driver: bridgebash启动服务docker-compose up -d查看日志docker-compose logs -f
基础配置与优化配置文件结构bashNginx配置文件结构/etc/nginx/├── nginx.conf # 主配置文件├── conf.d/ # 额外配置文件├── sites-available/ # 可用站点配置Ubuntu├── sites-enabled/ # 启用站点配置Ubuntu├── modules-available/ # 模块配置└── modules-enabled/ # 启用模块查看配置语法sudo nginx -t输出nginx: configuration file /etc/nginx/nginx.conf test is successful主配置文件优化nginx/etc/nginx/nginx.conf 关键优化user nginx; # 运行用户worker_processes auto; # 自动根据CPU核心设置pid /run/nginx.pid;events {worker_connections 1024; # 每个worker最大连接数multi_accept on; # 同时接受多个连接use epoll; # Linux高性能事件模型}http {# 基础设置sendfile on;tcp_nopush on;tcp_nodelay on;keepalive_timeout 65;types_hash_max_size 2048;server_tokens off; # 隐藏Nginx版本号# MIME类型 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; error_log /var/log/nginx/error.log warn; # Gzip压缩 gzip on; gzip_vary on; gzip_min_length 1024; gzip_types text/plain text/css application/json application/javascript text/xml; # 包含其他配置 include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; # Ubuntu}
创建虚拟主机bash创建站点配置sudo nano /etc/nginx/conf.d/mysite.confnginxserver {listen 80;server_name mysite.com www.mysite.com;# 网站根目录 root /var/www/mysite; index index.html index.php; # 日志 access_log /var/log/nginx/mysite.access.log; error_log /var/log/nginx/mysite.error.log; # 静态文件缓存 location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; add_header Cache-Control public, immutable; } # PHP处理如需要 location ~ \.php$ { fastcgi_pass unix:/var/run/php/php-fpm.sock; fastcgi_index index.php; include fastcgi_params; } # 禁止访问隐藏文件 location ~ /\. { deny all; } # 错误页面 error_page 404 /
html; error_page 500 502 503 504 /50x.html;}bash创建网站目录sudo mkdir -p /var/www/mysitesudo chown -RU S E R : USER:USER:USER /var/www/mysite创建测试页面echo “MySite is Running!” /var/www/mysite/index.html测试并重载配置sudo nginx -tsudo systemctl reload nginx
SSL证书配置HTTPS安装SSL证书Let’s Encryptbash安装Certbotsudo apt install certbot python3-certbot-nginx -y # Ubuntusudo dnf install certbot python3-certbot-nginx -y # CentOS 8获取证书自动配置Nginxsudo certbot --nginx -d mysite.com -d www.mysite.com测试自动续期sudo certbot renew --dry-run
手动配置SSLbash创建证书目录sudo mkdir -p /etc/nginx/ssl/mysitecd /etc/nginx/ssl/mysite生成自签名证书测试用sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048-keyout mysite.key -out mysite.crt-subj “/CCN/STBeijing/LBeijing/OMyCompany/CNmysite.com”nginxSSL站点配置server {listen 443 ssl http2;server_name mysite.com www.mysite.com;# SSL证书 ssl_certificate /etc/nginx/ssl/mysite/mysite.crt; ssl_certificate_key /etc/nginx/ssl/mysite/mysite.key; # SSL优化 ssl_protocols TLSv
2 TLSv
3; ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512; ssl_prefer_server_ciphers off; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; # HSTS头强制HTTPS add_header Strict-Transport-Security max-age31536000; includeSubDomains always; root /var/www/mysite; index index.html;}HTTP重定向到HTTPSserver {listen 80;server_name mysite.com www.mysite.com;return 301 https://s e r v e r n a m e server_nameservernamerequest_uri;}
负载均衡配置基础负载均衡nginxupstream backend {负载均衡算法轮询默认、最少连接、IP哈希least_conn; # 最少连接算法server backend
example.com:8080 weight3; # 权重3server backend
example.com:8080; # 权重1server backend
example.com:8080 backup; # 备份服务器}server {listen 80;server_name mysite.com;location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 健康检查 proxy_next_upstream error timeout invalid_header http_500 http_502 http_503; }}
高级负载均衡策略nginxupstream app_servers {zone backend 64k; # 共享内存区域# 会话保持IP哈希 ip_hash; server
192.
168.
101:8080 max_fails3 fail_timeout30s; server
192.
168.
102:8080 max_fails3 fail_timeout30s; server
192.
168.
103:8080 max_fails3 fail_timeout30s; # 健康检查需要nginx-plus或第三方模块 # health_check interval5 fails3 passes2;}
性能优化调优系统层优化bash调整文件描述符限制echo “nginx soft nofile 65535” | sudo tee -a /etc/security/limits.confecho “nginx hard nofile 65535” | sudo tee -a /etc/security/limits.conf调整内核参数cat /etc/sysctl.conf EOFNginx优化net.core.somaxconn 65535net.ipv
tcp_max_syn_backlog 65535net.core.netdev_max_backlog 32768net.ipv
tcp_tw_reuse 1net.ipv
tcp_tw_recycle 1EOFsudo sysctl -p
Nginx配置优化nginx工作进程优化worker_processes auto; # 自动设置为CPU核心数worker_rlimit_nofile 65535; # 每个worker文件描述符限制events {worker_connections 65535; # 增加连接数use epoll; # Linux高性能事件模型multi_accept on;}http {# 缓冲优化client_body_buffer_size 128k;client_max_body_size 20m;client_header_buffer_size 1k;large_client_header_buffers 4 4k;# 超时设置 client_body_timeout 12; client_header_timeout 12; send_timeout 10; # 静态文件缓存 open_file_cache max1000 inactive20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on;}
监控与日志分析启用状态监控nginx状态监控页面server {listen 8080;server_name localhost;location /nginx_status { stub_status on; access_log off; allow
127.
0.
1; # 只允许本地访问 deny all; }}bash访问状态页面curl http://localhost:8080/nginx_status输出Active connections: 1server accepts handled requests10 10 20Reading: 0 Writing: 1 Waiting: 0日志分析bash实时查看访问日志sudo tail -f /var/log/nginx/access.log统计访问量前10的IPawk ‘{print $1}’ /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10统计状态码awk ‘{print $9}’ /var/log/nginx/access.log | sort | uniq -c | sort -nr使用goaccess进行可视化分析sudo apt install goaccess -ygoaccess /var/log/nginx/access.log -o /var/www/html/report.html --log-formatCOMBINED
故障排除与维护
常见问题解决bash问题1端口被占用sudo netstat -tulnp | grep :80sudo kill -9 # 或修改Nginx端口问题2配置文件错误sudo nginx -t # 测试配置语法sudo nginx -T # 显示完整配置并测试问题3权限问题sudo chown -R nginx:nginx /var/www/mysitesudo chmod -R 755 /var/www/mysite问题4无法启动sudo journalctl -u nginx -f # 查看详细日志sudo dmesg | grep nginx # 查看内核日志
性能测试bash安装压力测试工具sudo apt install apache2-utils -y # Ubuntusudo yum install httpd-tools -y # CentOS压力测试ab -n 1000 -c 100 http://localhost/ # 1000请求100并发或使用wrk更强大sudo apt install wrk -ywrk -t4 -c100 -d10s http://localhost/
安全加固bash隐藏Nginx版本sed -i ‘s/# server_tokens off;/server_tokens off;/g’ /etc/nginx/nginx.conf限制请求方法location / {limit_except GET POST {deny all;}}防止DDoSlimit_req_zone $binary_remote_addr zoneone:10m rate1r/s;location / {limit_req zoneone burst5;}安装验证清单✅ 基础检查Nginx服务正常运行systemctl status nginx配置文件语法正确nginx -t端口监听正常ss -tuln | grep :80✅ 网站访问HTTP访问正常curl -I http://localhost自定义站点可访问错误页面正常显示✅ 安全配置版本信息已隐藏防火墙已配置SSL证书已安装如需✅ 性能优化工作进程数设置合理Gzip压缩已启用静态文件缓存已配置
总结建议安装方法选择生产环境 → 包管理器安装 官方仓库开发测试 → Docker容器部署特定需求 → 源码编译安装版本选择稳定优先 → Nginx
1.
x 稳定版功能最新 → Nginx
1.