1、下载
访问 Nginx官方下载网站 选择需要的版本进行下载:
2、安装
解压后进入源码目录,进行配置,主要是添加stream支持tcp代理:
./configure --with-stream
./configure --with-stream
配置完成后,进行编译和安装:
make
sudo make install
make sudo make install
至此就按照完成。
3、配置
主要是添加需要转发的规则,Nginx默认安装目录/usr/local/nginx/
默认配置文件:/usr/local/nginx/conf/nginx.conf
查看使用的配置文件:sudo /usr/local/nginx/sbin/nginx –t
指定配置文件:sudo /usr/local/nginx/sbin/nginx –c 配置文件绝对路径
先备份下默认配置,
sudo cp /usr/local/nginx/conf/nginx.conf -n /usr/local/nginx/conf/nginx.conf.back
再执行编辑
sudo gedit /usr/local/nginx/conf/nginx.conf
进行编辑,写入如下内容,根据需求更改IP和端口
worker_processes 1;
events {
worker_connections 1024;
}
stream{
server{
listen IP:端口; #监听端口
proxy_pass IP:端口; #转发端口
}
}
worker_processes 1;
events {
worker_connections 1024;
}
stream{
server{
listen IP:端口; #监听端口
proxy_pass IP:端口; #转发端口
}
}
可以创建多个server 处理多个代理。
4、自启动
Ubuntu-18.04使用systemd管理系统服务。用 systemctl 命令来替换了 service 和 chkconfig 的功能。
systemctl service服务文件夹在/lib/systemd/system(基本服务文件夹)与/etc/systemd/system(开机启动文件夹)。在/lib/systemd/system下创建nginx.service,执行:
sudo touch /lib/systemd/system/nginx.service
sudo gedit /lib/systemd/system/nginx.service
写入如下内容:
[Unit]
Description=nginx service
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
Restart=always
RestartSec=30
User=root
Group=root
TimeoutSec=0
[Install]
WantedBy=multi-user.target
Alias=nginx
[Unit] Description=nginx service After=network.target [Service] Type=forking ExecStart=/usr/local/nginx/sbin/nginx Restart=always RestartSec=30 User=root Group=root TimeoutSec=0 [Install] WantedBy=multi-user.target Alias=nginx
保存后添加权限:
sudo chmod 777 /lib/systemd/system/nginx.service
然后重新载入服务
sudo systemctl daemon-reload
开启自启动
sudo systemctl enable nginx.service
5、结束语
至此就配置完成了。
Nginx依赖网络因此需要再网络服务启动之后启动,其次Nginx启动需要关闭超时检测,否则会被检测到启动超时被Kill掉。
查看服务状态:
sudo systemctl status nginx.service
● nginx.service - nginx service
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: en
Active: active (running) since Sat 2022-04-23 17:07:51 CST; 196ms ago
Process: 2890 ExecStart=/usr/local/nginx/sbin/nginx (code=exited, status=0/SUC
Main PID: 2891 (nginx)
Tasks: 2 (limit: 11686)
CGroup: /system.slice/nginx.service
├─2891 nginx: master process /usr/local/nginx/sbin/nginx
└─2892 nginx: worker process
4月 23 17:07:51 machine systemd[1]: Starting nginx service...
4月 23 17:07:51 machine systemd[1]: Started nginx service.
查看运行状态
ps -ef | grep nginx
root 2891 1 0 17:07 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx nobody 2892 2891 0 17:07 ? 00:00:00 nginx: worker process xxx 2968 2751 0 17:44 pts/0 00:00:00 grep --color=auto nginx



