Linux 怎么设置开机自启?systemd service 完整做法
答案:系统服务用 systemctl enable --now <服务> 一次完成"开机自启 + 现在启动";自己的程序写一个 .service 单元到 /etc/systemd/system/,含 ExecStart 和 WantedBy=multi-user.target,再 daemon-reload 并 enable。
一、启用/关闭/查看
systemctl enable nginx # 设置开机自启(建立到 multi-user.target.wants 的软链)
systemctl enable --now nginx # 自启 + 立即启动(最常用)
systemctl disable nginx # 取消开机自启
systemctl start nginx # 仅当前启动(不影响开机)
systemctl stop nginx
systemctl restart nginx
systemctl status nginx # 状态/PID/最近日志
systemctl is-enabled nginx # enabled / disabled
systemctl is-active nginx # active / inactive| 操作 | 管什么 | 重启后 |
|---|---|---|
enable / disable | 开机是否自动拉起 | 影响 |
start / stop | 此刻运行状态 | 不影响开机策略 |
enable --now | 两者同时 | 立即运行且重启后仍在 |
常见误区:
start了服务以为重启还在(其实没 enable);或enable了但当前没启动(要加--now或再 start)。
二、把自己的程序做成服务
/etc/systemd/system/myapp.service:
[Unit]
Description=My Batch App
After=network.target
[Service]
Type=simple
User=deploy
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/python3 /opt/myapp/app.py
Restart=on-failure
RestartSec=3
Environment=APP_ENV=prod
# LimitNOFILE=65535 # 需要高并发时顺带放开 fd
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reload # 新增/改单元后必须 reload
sudo systemctl enable --now myapp
sudo systemctl status myapp
journalctl -u myapp -f # 看日志(见查看日志 FAQ)要点:
[Install] WantedBy=multi-user.target是 enable 的挂载点,缺它 enable 会报Does not have an InstallSection。ExecStart用绝对路径;环境变量用Environment=或EnvironmentFile=,不要假定有登录 shell 的 PATH(这点和 crontab 类似)。Restart=on-failure/always+RestartSec让进程崩了自动拉起,配合User=最小权限运行。- 改完单元一定
daemon-reload,否则 systemd 还用旧配置。
三、用户级服务
systemctl --user enable --now myuser.service
loginctl enable-linger 用户名 # 允许未登录时用户实例也运行(否则退出登录会停)放在
~/.config/systemd/user/的服务用--user管理;想让它在用户没登录时也跑,必须enable-linger,否则随用户会话结束而停止。
四、老系统与排查
- 老式 SysV:
chkconfig httpd on(RHEL)、update-rc.d(Debian),现代发行版仍由 systemd 兼容。 - 应急的
/etc/rc.local现在默认不推荐,需要的话要给它加执行位,且它在启动流程中较早、环境更简陋。 - 自启了但程序起不来:
systemctl status+journalctl -u 名 -xe看报错,重点查 ExecStart 路径、WorkingDirectory、依赖的After=、以及用户权限(日志排查见查看日志)。 - 想查开机耗时和启动项:
systemd-analyze blame、systemctl list-unit-files --state=enabled。
FAQ
Q: 怎么开机自启? A: systemctl enable --now 服务(自启并立即启动),取消用 disable。
Q: 怎么确认自启? A: is-enabled 看开机策略、is-active 看当前状态、status 综合查看。
Q: 自己的程序怎么做? A: 写 /etc/systemd/system/xx.service,含 ExecStart 与 [Install] WantedBy=multi-user.target,daemon-reload 后 enable --now。
Q: enable 报没有 InstallSection? A: 缺 [Install] 段,补 WantedBy=multi-user.target 再 daemon-reload、enable。
Q: enable 和 start 区别? A: enable 管开机自启(不改变当前),start 管当前运行(不管重启),--now 一次两者都做。
一句话总结:系统服务 systemctl enable --now 同时设自启并启动,is-enabled/status 确认;自定义程序写 .service(绝对路径 ExecStart + Restart + WantedBy=multi-user.target)后 daemon-reload 再 enable;用户级用 --user 且需 linger,起不来查 status/journalctl。