Ubuntu24.04 编译安装 Nginx

407 阅读1分钟

Ubuntu24.04 编译安装 Nginx

本文将给出基于 ubuntu24.04系统通过编译安装 Nginx 1.26.2 , 并将其配置为系统服务的完整方法。

Nginx 官网: nginx.org/en/download…

1.安装前置依赖

1.1 gcc 安装

cd ~
apt update
apt install build-essential libpcre3-dev libssl-dev
gcc --version

1.2 prce 安装

wget https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.44/pcre2-10.44.tar.gz
tar -zxvf pcre2-10.44.tar.gz
cd pcre2-10.44/

sudo ./configure --prefix=/opt/app/pcre2
sudo make 
sudo make install

1.3 zlib 安装

cd ~
wget https://github.com/madler/zlib/releases/download/v1.3.1/zlib-1.3.1.tar.gz
tar -zxvf zlib-1.3.1.tar.gz
cd zlib-1.3.1/

sudo ./configure --prefix=/opt/app/zlib
sudo make 
sudo make install

1.4 openssl 安装

cd ~
wget https://github.com/openssl/openssl/releases/download/openssl-3.3.1/openssl-3.3.1.tar.gz
tar -zxvf openssl-3.3.1.tar.gz
cd openssl-3.3.1/

sudo ./config --prefix=/opt/app/openssl
sudo make 
sudo make install

2 安装 nginx 1.26.2(当前最新版)

cd ~
wget https://nginx.org/download/nginx-1.26.2.tar.gz
tar -zxvf nginx-1.26.2.tar.gz
cd nginx-1.26.2/

nginx 编译安装到指定位置,如:/opt/app/nginx

sudo ./configure \
--prefix=/opt/app/nginx \
--with-pcre=../pcre2-10.44 \
--with-zlib=../zlib-1.3.1 \
--with-openssl=../openssl-3.3.1 \
--with-stream \
--with-stream_ssl_preread_module \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module
sudo make && make install

到此完成安装。

测试启动:

cd /opt/app/nginx
sudo ./sbin/nginx

测试访问:http://本机ip:80 ,正常输出:

image.png

3.任意位置执行命令

创建软连接,以实现任意位置执行命令

软连接用于解决任意位置可以执行 nginx 命令

ln -s /opt/app/nginx/sbin/nginx /usr/local/sbin/nginx

任意位置测试:

# nginx -v
nginx version: nginx/1.26.2

4.配置为系统服务

4.1 执行命令

sudo vim /etc/systemd/system/nginx.service

在文件中写入以下内容并保存:

[Unit]
Description = nginx daemon

[Service]
ExecStart = /opt/app/nginx/sbin/nginx
ExecStop = /opt/app/nginx/sbin/nginx -s stop
ExecReload = /opt/app/nginx/sbin/nginx -s reload
Restart = always
Type = forking

[Install]
WantedBy = multi-user.target  

4.2 测试服务

测试命令

# systemctl daemon-reload
# systemctl status nginx
# syttemctl start nginx
# systemctl enable nginx
# systemctl restart nginx
# systemctl stop nginx

# nginx -V

命令执行记录

# systemctl daemon-reload

查看 nginx 服务状态

# syttemctl start nginx
# systemctl status nginx

# systemctl stop nginx
# systemctl status nginx

# systemctl restart nginx
# systemctl status nginx