systemd (现代Linux发行版)
systemctl start|stop|restart|status|enable|disable 服务名
SysVinit (旧版系统)
service 服务名 start|stop|restart|status
chkconfig 服务名 on|off
systemctl list-units --type=service # 查看所有服务
systemctl list-unit-files --type=service # 查看服务启动状态
sudo systemctl disable 服务名 # 禁用开机启动
sudo systemctl stop 服务名 # 立即停止服务
常见可禁用服务(根据实际需求): - bluetooth - cups (打印服务) - avahi-daemon (零配置网络) - postfix (邮件服务,如不使用)
sudo systemctl edit 服务名
在编辑器中添加:
[Unit]
After=network.target
Wants=network.target
在/etc/systemd/system.conf
中设置:
DefaultLimitNOFILE=65535
DefaultLimitNPROC=65535
或针对特定服务:
[Service]
LimitNOFILE=65535
LimitNPROC=65535
sudo nice -n -5 /path/to/service # 提高优先级
sudo renice -5 -p PID # 调整运行中进程
echo 1 > /proc/sys/vm/overcommit_memory # 激进内存分配策略
echo 80 > /proc/sys/vm/vfs_cache_pressure # 减少inode缓存回收
对于Nginx/Apache等:
worker_processes auto; # 自动设置工作进程数
worker_connections 1024; # 每个进程连接数
keepalive_timeout 65; # 保持连接时间
[Service]
User=specialuser
Group=specialgroup
PrivateTmp=yes
ProtectSystem=full
journalctl -u 服务名 -f # 实时查看日志
journalctl -u 服务名 --since "1 hour ago" # 查看近期日志
配置日志轮转:
/etc/logrotate.d/自定义配置
sudo systemctl status 服务名
top -p $(pgrep -d',' 服务名)
htop # 交互式进程查看
iotop # I/O监控
nethogs # 网络流量监控
使用cron定时任务:
0 3 * * * /usr/bin/systemctl restart 关键服务
taskset -c 0,1 /path/to/service # 绑定到特定CPU核心
/etc/sysctl.conf 中添加:
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
vm.swappiness = 10
systemd-run --unit=limited-service --scope -p MemoryLimit=500M /path/to/service
systemctl daemon-reload
通过以上优化措施,可以显著提升Linux系统中服务的性能和稳定性,同时增强系统安全性。