由于最近使用golang重写了博客,因为博客中需要用到html模版文件和静态文件所以启动时候就会有些麻烦。每次版本更新都把Linux的二进制包和静态资源,模版文件打包上传到服务器;再进入项目解压目录执行程序,这一波操作相对的麻烦。如果系统重启了,还要手动去启动服务。


为了简化这操作,简单的写两个脚本实现系统开机启动服务;


简单粗暴的脚本blog:我习惯存放在/etc/init.d/目录下


#!/bin/env bash# AuthName:swper# Website:http://www.58jb.com# DateTime:2019-05-22# description: Golang 程序启动脚本.. /etc/init.d/functions
RETVAL=$?# Go程序的目录[根据自己存放地址修改]export GO_APP="/usr/local/openresty/nginx/html/blog58"#可执行文件名称[就是打包后的程序执行文件]export APP_NAME="blog58"# 可选PID=ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}'case "$1" instart)if [ -f $GO_APP/$APP_NAME ];then
    echo $"Start app"
    cd $GO_APP
    nohup ./$APP_NAME >/tmp/${APP_NAME}.log 2>&1 &fi;;
stop)if [ -f $GO_APP/$APP_NAME ];then
    echo $"Stop app"
    kill -9 $PIDfi;;
*)    echo $"Usage: $0 {start|stop}"
    exit 1;;esacexit $RETVAL

给脚本添加一个可执行权限:


[root@VM_0_5_centos ~]# chmod +x /etc/init.d/blog

因为是Centos7系统,再加了一个/lib/systemd/system/goapp.service 执行文件:


[Unit]Description="golang app Service "After=network.target[Service]Type=forkingExecStart=/bin/bash /etc/init.d/blog startExecStop=/bin/bash /etc/init.d/blog stopKillSignal=SIGQUITTimeoutStopSec=5KillMode=processPrivateTmp=true[Install]WantedBy=multi-user.target

最后添加到开机启动:


[root@VM_0_5_centos ~]# systemctl enable goappCreated symlink from /etc/systemd/system/multi-user.target.wants/goapp.service to /usr/lib/systemd/system/goapp.service.

重启系统后就可以看到服务已经在运行了。