linux 如何设置某个服务自启动?

设置某个服务在linux服务器重新启动的时候自启动,可以使用 systemctl enable 服务名 ,例如要设置nginx 自启动可以使用 systemctl enable nginx 来进行设置

可以用systemctl disable nginx, 前提是nginx的service脚本已经配置,yum安装会自动配置好,编译安装的需要手动编辑脚本文件。


systemctl 能控制启动的服务,在/usr/lib/systemd/system 目录下必须有相应脚本,以service结尾

脚本格式如下:

[root@VM_0_3_centos system]# pwd
/usr/lib/systemd/system
[root@VM_0_3_centos system]# more  postfix.service
[Unit]
Description=Postfix Mail Transport Agent
After=syslog.target network.target
Conflicts=sendmail.service exim.service

[Service]
Type=forking
PIDFile=/var/spool/postfix/pid/master.pid
EnvironmentFile=-/etc/sysconfig/network
ExecStartPre=-/usr/libexec/postfix/aliasesdb
ExecStartPre=-/usr/libexec/postfix/chroot-update
ExecStart=/usr/sbin/postfix start
ExecReload=/usr/sbin/postfix reload
ExecStop=/usr/sbin/postfix stop

[Install]
WantedBy=multi-user.target
[root@VM_0_3_centos system]# systemctl enable postfix      //设置开机启动,成功提示如下
Created symlink from /etc/systemd/system/multi-user.target.wants/postfix.service to /usr/lib/systemd/system/postfix.service.

如果服务启动脚本不存在:

[root@VM_0_3_centos system]# systemctl enable nginx
Failed to execute operation: No such file or directory