开机自启动方法一:

    编辑 vi /lib/systemd/system/nginx.service 文件,没有创建一个 touch nginx.service 然后将如下内容根据具体情况进行修改后,添加到nginx.service文件中:

    1. [Unit]
    2. Description=nginx
    3. After=network.target remote-fs.target nss-lookup.target
    4. [Service]
    5. Type=forking
    6. PIDFile=/var/run/nginx.pid
    7. ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
    8. ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
    9. ExecReload=/bin/kill -s HUP $MAINPID
    10. ExecStop=/bin/kill -s QUIT $MAINPID
    11. PrivateTmp=true
    12. [Install]
    13. WantedBy=multi-user.target
    • [Unit]:服务的说明
    • Description:描述服务
    • After:描述服务类别
    • [Service]服务运行参数的设置
    • Type=forking是后台运行的形式
    • ExecStart为服务的具体运行命令
    • ExecReload为重启命令
    • ExecStop为停止命令
    • PrivateTmp=True表示给服务分配独立的临时空间 注意:[Service]的启动、重启、停止命令全部要求使用绝对路径。

    [Install]运行级别下服务安装的相关设置,可设置为多用户,即系统运行级别为3

    保存退出。

    设置开机启动,使配置生效:

    1. # 启动nginx服务
    2. systemctl start nginx.service
    3. # 停止开机自启动
    4. systemctl disable nginx.service
    5. # 查看服务当前状态
    6. systemctl status nginx.service
    7. # 查看所有已启动的服务
    8. systemctl list-units --type=service
    9. # 重新启动服务
    10. systemctl restart nginx.service
    11. # 设置开机自启动
    12. systemctl enable nginx.service
    13. # 输出下面内容表示成功了
    14. Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
    1. systemctl is-enabled servicename.service # 查询服务是否开机启动
    2. systemctl enable *.service # 开机运行服务
    3. systemctl disable *.service # 取消开机运行
    4. systemctl start *.service # 启动服务
    5. systemctl stop *.service # 停止服务
    6. systemctl restart *.service # 重启服务
    7. systemctl reload *.service # 重新加载服务配置文件
    8. systemctl status *.service # 查询服务运行状态
    9. systemctl --failed # 显示启动失败的服务

    注:*代表某个服务的名字,如http的服务名为httpd

    开机自启动方法二:

    1. vi /etc/rc.local
    2. # 在 rc.local 文件中,添加下面这条命令
    3. /usr/local/nginx/sbin/nginx start

    如果开机后发现自启动脚本没有执行,你要去确认一下rc.local这个文件的访问权限是否是可执行的,因为rc.local默认是不可执行的。修改rc.local访问权限,增加可执行权限:

    1. # /etc/rc.local是/etc/rc.d/rc.local的软连接,
    2. chmod +x /etc/rc.d/rc.local

    官方脚本 ed Hat NGINX Init Script