linux设置开启启动服务

方法一:编辑/etc/rc.local,添加开机启动运行命令;

直接编辑/etc/rc.local文件,文件内容最底下添加启动命令

复制代码
[root@hello ~]# vi /etc/rc.local 
# 最后追加内容,根据实际情况修改
/usr/sbin/nginx -c /etc/nginx/nginx.conf &

方法二: 使用注册系统服务(systemctl)(推荐):

1. 知识扩展

CentOS7的服务systemctl脚本存放在:/usr/lib/systemd/,有系统(system)和用户(user)之分:

复制代码
  /usr/lib/systemd/system (系统服务,开机不需要登录就能运行)
  /usr/lib/systemd/user (用户服务,需要登录后才能运行)

/usr/lib/systemd/system 和 /etc/systemd/system的区别:

复制代码
  对于那些支持 Systemd(YUM/DNF/RPM/APT/etc) 的软件,安装的时候,会自动在 /usr/lib/systemd/system 目录添加一个配置文件。
  对于非软件包形式的临时软件安装,系统操作员应将文件手动放置在 /etc/systemd/system

注意: 设置开机自启动脚本可以在/etc/systemd/system或者/usr/lib/systemd/system目录下配置,当两个地方都配置了的情况下,/etc/systemd/system配置优先。

3.每一个服务以.service结尾,一般会分为3部分:UnitServiceInstallUnit 主要是对这个服务的说明,内容包括Description和After,Description用于描述服务,After用于描述服务类别。 Service 是服务的关键,是服务的一些具体运行参数的设置,

复制代码
Type=forking是后台运行的形式
PIDFile 为存放PID的文件路径
ExecStart 为服务的具体运行命令
ExecReload 为重启命令
ExecStop 为停止命令
PrivateTmp=True 表示给服务分配独立的临时空间
  1. 以nginx为例: 新建nginx服务文件

    vim /etc/systemd/system/nginx.service

文件内容如下:

复制代码
[Unit]
Description=nginx
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/tengine/sbin/nginx    #修改为自己系统对应的路径
ExecReload=/usr/local/tengine/sbin/nginx -s reload #修改为自己系统对应的路径
ExecStop=/usr/local/tengine/sbin/nginx -s quit    #修改为自己系统对应的路径
PrivateTmp=true
[Install]
WantedBy=multi-user.target
  1. 设置开机自动启动 systemctl enable nginx.service

    systemctl start nginx.service #开启
    systemctl stop nginx.service #关闭
    systemctl reload nginx.service #重新加载配置
    systemctl status nginx.service #查看状态

以下是普通java后台注册系统服务文件:

复制代码
[Unit]
Description=Java daemon demo
After=syslog.target network.target

[Service]
User=huangjf
Group=huangjf
Type=simple
WorkingDirectory=/opt/perfree/
ExecStart=/usr/bin/java -jar perfree-web.jar
ExecStop=/bin/kill -15 $MAINPID

[Install]
WantedBy=multi-user.target

修改后重新加载服务文件:

复制代码
systemctl daemon-reload
相关推荐
未济2 天前
linux 配置环境变量
linux
傲世仙尊2 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
还是大剑师兰特2 天前
解决nginx错误:http://localhost:7000正常,http://localhost:7000/map 报错404
nginx·大剑师
_艾伦 耶格尔.2 天前
进程间通信
linux
AI职业加油站2 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
Liuqy-052 天前
Linux IO编程——静态库、动态库
linux
此冬歌咏2 天前
K8s 节点故障实战:优雅驱逐 31 秒,硬故障 331 秒,以及那个永远 Pending 的 Pod
运维·k8s
彧azz2 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
xing-xing2 天前
Docker容器中Nginx站点根目录网页配置访问
nginx·docker