服务操作
使用systemctl命令
1. 列出所有服务
使用 systemctl
命令
1 | systemctl list-units --type=service |
list-units
:列出所有已加载的单元(服务、套接字、目标等)--type=service
:仅列出服务类型的单元
开机启动的服务
1 | systemctl list-unit-files --type=service | grep enabled |
2. 启动服务
1 | sudo systemctl start nginx |
3. 停止服务1
sudo systemctl stop nginx
4. 重启服务
1 | sudo systemctl restart nginx |
5. 重新加载配置文件
如果服务支持重新加载配置文件(通常用于不停止服务的情况下更新配置),可以使用:1
sudo systemctl reload nginx
6. 查看服务状态1
systemctl status nginx
7. 设置服务开机自启动1
sudo systemctl enable nginx
8. 取消服务开机自启动1
sudo systemctl disable nginx
9. 查看服务日志
使用 journalctl
命令
1 | journalctl -u nginx |
-u nginx
:指定要查看的服务
10. 修改服务配置文件
服务配置文件通常位于 /etc/systemd/system/
或 /lib/systemd/system/
目录下。
编辑服务配置文件1
sudo vi /etc/systemd/system/nginx.service
重新加载 systemd 配置
1 | sudo systemctl daemon-reload |
注意事项
- 使用
systemctl
命令时,确保服务名正确。 - 修改服务配置文件后,记得重新加载 systemd 配置。
- 某些操作(如
start
、stop
、restart
)需要 root 权限。
这些操作可以帮助你有效地管理和维护 Linux 系统中的服务。
使用 service
命令
虽然 systemctl
是现代的 systemd 管理工具,但仍然可以使用旧的 service
命令来管理服务。
查看服务列表
1 | chkconfig --list |
启动服务
1 | sudo service nginx start |
停止服务
1 | sudo service nginx stop |
重启服务
1 | sudo service nginx restart |
查看服务状态
1 | sudo service nginx status |
查看进程
进程列表
列表展示
1 | ps -ef |
列表展示
1 | ps -ef | grep nginx |
树状显示进程
1 | pstree |
通过端口查看
1 | lsof -i:80 |
端口IP范围
查看端口监听IP范围
1 | netstat -tuln | grep :80 |
或者
1 | sudo ss -tuln | grep :80 |
端口及进程
查看监听的端口
1 | lsof -i -P -n | grep LISTEN |
查看进程监听的端口
1 | lsof -i -P -n | grep LISTEN | grep java |
开机服务查看
在 Linux 系统中,可以通过多种方式查看开机启动的服务。
以下是几种常见的方法:
systemd 系统的服务
使用 systemctl
命令systemctl
是 systemd 系统的服务管理工具,可以用来查看和管理开机启动的服务。
查看所有开机启动的服务1
systemctl list-unit-files --type=service | grep enabled
list-unit-files
:列出所有单元文件及其状态--type=service
:仅列出服务类型的单元文件grep enabled
:过滤出已启用的服务
查看 /etc/systemd/system/
和 /lib/systemd/system/
目录
systemd 服务通常会放在这两个目录下,可以通过以下命令查看:
1 | ls /etc/systemd/system/ |
chkconfig
查看 chkconfig
列表(适用于 CentOS/RHEL 系统)chkconfig
是一个用于管理不同运行级别下的服务启动状态的工具。
1 | chkconfig --list |
查看 /etc/init.d/
目录
在传统的 SysV 初始化系统中,开机启动的服务会放在 /etc/init.d/
目录下。
1 | ls /etc/init.d/ |
查看 /etc/rc.d/rc*.d/
目录
这些目录中包含了指向 /etc/init.d/
目录中脚本的符号链接,这些链接决定了服务在不同运行级别(runlevel)下的启动顺序。
1 | ls /etc/rc.d/rc*.d/ |
rc.local
查看 /etc/rc.local
文件
在某些系统中,用户自定义的开机启动脚本可能会放在 /etc/rc.local
文件中。
1 | cat /etc/rc.local |