配置文件

创建服务

1
vi /usr/lib/systemd/system/nginx.service

编辑文件,配置 nginx 程序所在目录

1
2
3
4
5
6
7
8
9
10
11
12
13
[Unit]
Description=nginx
After=network.target

[Service]
Type=forking
ExecStart=/www/server/nginx/sbin/nginx
ExecReload=/www/server/nginx/sbin/nginx -s reload
ExecStop=/www/server/nginx/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target

常用命令

设置开机自启

1
2
3
4
5
6
7
8
# 更新配置
systemctl daemon-reload

# 启动服务
systemctl start nginx

# 设置开机启动
systemctl enable nginx

管理命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 启动服务
systemctl start nginx

# 停止服务
systemctl stop nginx

# 重启服务
systemctl restart nginx

# 查看状态
systemctl status nginx

# 取消开机启动
systemctl disable nginx

遇到的错误解决

碰到了端口被占用的问题

[root@sg conf]# systemctl status nginx
● nginx.service - nginx
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: failed (Result: exit-code) since 一 2021-07-12 15:11:45 CST; 6s ago
Process: 1705 ExecStart=/www/server/nginx/sbin/nginx (code=exited, status=1/FAILURE)

7 月 12 15:11:45 sg systemd[1]: Starting nginx…
7 月 12 15:11:45 sg nginx[1705]: nginx: [emerg] duplicate location “/“ in /www/server/nginx/conf/…nf:48
7 月 12 15:11:45 sg systemd[1]: nginx.service: control process exited, code=exited status=1
7 月 12 15:11:45 sg systemd[1]: Failed to start nginx.
7 月 12 15:11:45 sg systemd[1]: Unit nginx.service entered failed state.
7 月 12 15:11:45 sg systemd[1]: nginx.service failed.

netstat 命令

netstat 命令用于显示网络状态,centos7 默认没有 netstat 命令,需要安装 net-tools 工具

1
yum install -y net-tools

查看监听的端口

1
netstat -lnpt

[root@sg conf]# netstat -lnpt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:80 0.0.0.0:_ LISTEN 1747/nginx: master
tcp 0 0 0.0.0.0:22 0.0.0.0:_ LISTEN 1108/sshd
tcp 0 0 127.0.0.1:25 0.0.0.0:_ LISTEN 1379/master
tcp6 0 0 :::9105 :::_ LISTEN 1488/cloudreve
tcp6 0 0 :::22 :::_ LISTEN 1108/sshd
tcp6 0 0 ::1:25 :::_ LISTEN 1379/master
tcp6 0 0 :::443 :::* LISTEN 1488/cloudreve

检查端口被哪个进程占用

1
netstat -lnpt |grep 80

[root@sg conf]# netstat -lnpt |grep 80
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1747/nginx: master

查看进程的详细信息

1
ps 1747

[root@sg conf]# ps 1747
PID TTY STAT TIME COMMAND
1747 ? Ss 0:00 nginx: master process /www/server/nginx/sbin/nginx

中止进程

1
kill -9 1747