# 启动服务
sudo systemctl start service_name
# 停止服务
sudo systemctl stop service_name
# 重启服务
sudo systemctl restart service_name
# 查看服务状态
sudo systemctl status service_name
# 启用开机自启
sudo systemctl enable service_name
# 禁用开机自启
sudo systemctl disable service_name
# 查看所有已启用服务
systemctl list-unit-files --state=enabled
# 启动服务
sudo service service_name start
# 停止服务
sudo service service_name stop
# 重启服务
sudo service service_name restart
# 查看服务状态
sudo service service_name status
# 启用开机自启
sudo chkconfig service_name on
# 禁用开机自启
sudo chkconfig service_name off
# 查看运行级别设置
sudo chkconfig --list
/etc/systemd/system/
(自定义服务) 和 /lib/systemd/system/
(系统服务)/etc/init.d/
和 /etc/rc*.d/
(运行级别链接)# 实时监控系统资源
top
htop # 需要安装,更友好的界面
# 查看内存使用
free -h
# 查看磁盘使用
df -h
# 查看磁盘I/O
iotop # 需要安装
# 查看systemd服务日志
journalctl -u service_name
# 查看特定时间段的日志
journalctl --since "2023-01-01" --until "2023-01-02"
# 实时跟踪日志
journalctl -f -u service_name
# 传统日志文件位置
/var/log/syslog
/var/log/messages
/var/log/service_name/
# 分析系统启动时间
systemd-analyze
systemd-analyze blame # 显示各服务启动耗时
systemd-analyze critical-chain service_name # 显示服务依赖链
# 并行启动服务(在systemd配置中设置)
# 编辑/etc/systemd/system.conf
# 取消注释并修改:
# DefaultTimeoutStartSec=90s
# 使用systemd限制服务资源
# 编辑服务单元文件(/etc/systemd/system/service_name.service)
[Service]
MemoryLimit=512M
CPUQuota=50%
# 查看服务依赖关系
systemctl list-dependencies service_name
# 修改服务依赖(在服务单元文件中)
[Unit]
After=network.target
Requires=network.target
# 临时修改内核参数
sysctl -w parameter=value
# 永久修改(编辑/etc/sysctl.conf)
# 例如优化网络性能:
net.core.rmem_max=4194304
net.core.wmem_max=4194304
net.ipv4.tcp_rmem=4096 87380 4194304
net.ipv4.tcp_wmem=4096 16384 4194304
# 调整文件系统挂载选项(在/etc/fstab中)
# 例如添加noatime,nodiratime选项:
UUID=xxx / ext4 defaults,noatime,nodiratime 0 1
# 设置定期日志轮转(编辑/etc/logrotate.conf)
# 配置定期清理临时文件
# 为服务创建专用用户
sudo useradd -r -s /bin/false service_user
# 在服务配置中指定用户
[Service]
User=service_user
Group=service_group
# 使用systemd命名空间隔离
[Service]
PrivateTmp=true
PrivateNetwork=true
ProtectSystem=full
# 检查不必要的服务
systemctl list-unit-files | grep enabled
# 使用安全扫描工具
sudo apt install lynis # Debian/Ubuntu
sudo yum install lynis # RHEL/CentOS
sudo lynis audit system
- name: Ensure service is running and enabled
hosts: all
tasks:
- name: Ensure service is enabled and running
service:
name: service_name
state: started
enabled: yes
# 使用Prometheus + Grafana监控服务
# 或使用Nagios/Zabbix设置服务监控
通过以上方法,您可以有效地管理和优化Linux系统服务,提高系统性能和安全性。根据具体应用场景选择适合的优化策略,并定期审查服务配置以确保系统处于最佳状态。