一、环境与依赖准备
为确保编译顺利,我们首先更新系统并安装必要的编译工具和库:
sudo apt update sudo apt install -y build-essential \ libpcre3 libpcre3-dev \ zlib1g zlib1g-dev \ libssl-dev \ wget
build-essential
:提供gcc
、make
等基础编译工具libpcre3
/libpcre3-dev
:支持正则匹配(如rewrite
模块)zlib1g
/zlib1g-dev
:提供 gzip 压缩功能libssl-dev
:开启 https/ssl 支持wget
:用于下载源码包
二、下载并解压 nginx 源码
- 切换到用户主目录(或其他工作目录)
- 下载并解压源码包
cd ~ wget http://nginx.org/download/nginx-1.28.0.tar.gz tar zxvf nginx-1.28.0.tar.gz cd nginx-1.28.0
若你已将源码包 nginx-1.28.0.tar.gz
放在本地目录,同样执行 tar zxvf
并进入解压后的目录即可。
三、配置编译选项
使用 ./configure
脚本为编译过程指定安装路径和所需模块。
本例中启用了 http、ssl、http/2、gzip、状态监控、异步 i/o、线程以及 stream 模块等常用功能:
./configure \ --prefix=/usr/local/nginx \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_gzip_static_module \ --with-http_stub_status_module \ --with-http_realip_module \ --with-threads \ --with-file-aio \ --with-stream \ --with-stream_ssl_module \ --with-stream_realip_module
--prefix
:指定安装目录--with-http_stub_status_module
:开启运行状态页(可用于监控)- 其余模块可根据实际需求增删。执行
./configure --help
可查看所有可选项。
四、编译与安装
- 编译:根据机器性能,执行时间通常在几分钟左右
- 安装:将编译成果复制到指定目录
make sudo make install
- 编译完成后,可执行文件位于
/usr/local/nginx/sbin/nginx
- 默认主配置文件:
/usr/local/nginx/conf/nginx.conf
- 日志目录:
/usr/local/nginx/logs/
五、创建 systemd 服务单元
为了方便开机自启及系统统一管理,建议新建一个 systemd 服务文件:
sudo tee /etc/systemd/system/nginx.service > /dev/null << 'eof' [unit] description=nginx http and reverse proxy server after=network.target [service] type=forking execstart=/usr/local/nginx/sbin/nginx execreload=/usr/local/nginx/sbin/nginx -s reload execstop=/usr/local/nginx/sbin/nginx -s quit pidfile=/usr/local/nginx/logs/nginx.pid privatetmp=true [install] wantedby=multi-user.target eof
随后执行:
sudo systemctl daemon-reload sudo systemctl enable nginx
六、启动、重载与状态检查
- 启动 nginx
sudo systemctl start nginx
- 查看运行状态
sudo systemctl status nginx
- 平滑重载配置(修改
nginx.conf
后)
sudo systemctl reload nginx
- 停止 nginx
sudo systemctl stop nginx
七、防火墙设置与访问验证
如果系统启用了 ufw 防火墙,请放行 http/https 端口:
sudo ufw allow 80/tcp sudo ufw allow 443/tcp
在浏览器中访问服务器 ip 或绑定的域名,若出现默认 nginx 欢迎页,即代表安装部署成功。
八、常见故障排查
端口被占用
sudo lsof -i:80
如有其他服务占用,需停止或修改 nginx 监听端口。
配置文件语法错误
/usr/local/nginx/sbin/nginx -t
检查并修正错误后再重载。
日志查看
- 访问日志:
/usr/local/nginx/logs/access.log
- 错误日志:
/usr/local/nginx/logs/error.log
总结
本文详细介绍了在 ubuntu 上从源码编译安装 nginx 1.28.0 的全流程,涵盖依赖环境准备、源码下载解压、配置编译选项、make 安装、systemd 服务管理及常见排错方法。
通过这种方式,你可以根据业务需求灵活定制 nginx 功能,并更好地集成到生产运维体系中。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论