一般有兩種方式:
1.
1.1在etc/init.d/下新建服務名,例如,nginx,redis等
1.2 編輯相應的服務腳本,每個腳本可能不一,百度一下就有,更改自己的程序的配置文件,下面以haproxy爲例,說明方法
1.2.1 vim /etc/init.d/haproxy
1.2.2 編輯腳本,注意更改自己的配置文件
#!/bin/bash
haproxy
chkconfig: 35 85 15
description: HAProxy is a free, very fast and reliable solution \
offering high availability, load balancing, and \
proxying for TCP and HTTP-based applications
processname: haproxy
config: /etc/haproxy.cfg
pidfile: /var/run/haproxy.pid
Source function library.
. /etc/rc.d/init.d/functions
Source networking configuration.
. /etc/sysconfig/network
Check that networking is up.
[ “$NETWORKING” = “no” ] && exit 0
config="/usr/app/haproxy/etc/haproxy.cfg" //更改成自己的程序的配置文件
exec="/usr/app/haproxy/sbin/haproxy" //更改成自己的程序的配置文件
prog=$(basename $exec)
[ -e /etc/sysconfig/KaTeX parse error: Expected 'EOF', got '&' at position 8: prog ] &̲& . /etc/syscon…prog
1.3 這樣就可以啓動了
1.3.1 啓動方式:service haproxy start|stop
1.3.2 chkconfig –level haproxy 3456 註冊成系統服務,其中2345是自己可以選擇的級別
2
2.2 在lib/systemd/system/新建服務 如 vim nginx.service
2.3 編寫腳本文件
2.4 下面以nginx爲例
2.4.1cd /lib/systemd/system/
2.4.2vim nginx.service
2.4.3編輯內容如下
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
ExecStart=/var/nginx
ExecReload=/var/nginx/nginx -s reload
ExecStop=/var/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
一些說明:
[Unit]:服務的說明,對該系統服務描述及說明模塊
Description:描述服務
After:描述服務類別
[Service]服務運行參數的設置
Type=forking是後臺運行的形式,服務類型,可選有forking、notify、simple等
ExecStart爲服務的具體運行命令
ExecReload爲重啓命令
ExecStop爲停止命令
PrivateTmp=True表示給服務分配獨立的臨時空間
注意:[Service]的啓動、重啓、停止命令全部要求使用絕對路徑
[Install]運行級別下服務安裝的相關設置,可設置爲多用戶,即系統運行級別爲3
保存退出
2.4.4
加入開機自啓動
systemctl enable nginx.service
如果不想開機自啓動了,可以使用下面的命令取消開機自啓動。
systemctl disable nginx.service
systemctl start nginx.service 啓動nginx
systemctl stop nginx.service 結束nginx
systemctl restart nginx.service 重啓nginx、
2.4.5
說明(第一次啓動會出現的問題)
說明第一次啓動會提示以下報錯:
[root@server nginx-1.8.1]# systemctl restart nginx.service
Warning: nginx.service changed on disk. Run ‘systemctl daemon-reload’ to reload units.
Job for nginx.service failed because the control process exited with error code. See “systemctl status nginx.service” and “journalctl -xe” for details.
執行下面的命令重新載入 systemd,掃描新的或有變動的單元即可:
systemctl daemon-reload
#重新載入 systemd,掃描新的或有變動的單元