使用 Go 添加启动脚本

简介

虽然 Makefile 能很好的整合各类命令, 是一个很是方便的工具. 但启动脚本也是必不可少的, Makefile 更多用于开发阶段, 好比编译, 单元测试等流程.git

启动脚本的做用是控制程序的状态, 管理程序的启动, 中止, 查询运行状态等.github

实践

直接上脚本了:golang

#!/bin/bash 
SERVER="web"
BASE_DIR=$PWD
INTERVAL=2

# 命令行参数,须要手动指定, 这是在 docker 容器中运行的参数
ARGS="-c $BASE_DIR/conf/config_docker.yaml"

function start()
{
	if [ "`pgrep $SERVER -u $UID`" != "" ];then
		echo "$SERVER already running"
		exit 1
	fi

	nohup $BASE_DIR/$SERVER $ARGS >/dev/null 2>&1 &
	echo "sleeping..." &&  sleep $INTERVAL

	# check status
	if [ "`pgrep $SERVER -u $UID`" == "" ];then
		echo "$SERVER start failed"
		exit 1
  else
    echo "start success"
	fi
}

function status()
{
	if [ "`pgrep $SERVER -u $UID`" != "" ];then
		echo $SERVER is running
	else
		echo $SERVER is not running
	fi
}

function stop()
{
	if [ "`pgrep $SERVER -u $UID`" != "" ];then
		kill `pgrep $SERVER -u $UID`
	fi

	echo "sleeping..." &&  sleep $INTERVAL

	if [ "`pgrep $SERVER -u $UID`" != "" ];then
		echo "$SERVER stop failed"
		exit 1
  else
    echo "stop success"
	fi
}

function version()
{
  $BASE_DIR/$SERVER $ARGS version
}

case "$1" in
	'start')
	start
	;;
	'stop')
	stop
	;;
	'status')
	status
	;;
	'restart')
	stop && start
	;;
  'version')
  version
  ;;
	*)
	echo "usage: $0 {start|stop|restart|status|version}"
	exit 1
	;;
esac
复制代码

用法以下:web

  • ./admin.sh start 启动
  • ./admin.sh stop 中止
  • ./admin.sh restart 重启
  • ./admin.sh status 查看状态
  • ./admin.sh version 查看版本

困惑

在运行启动脚本的过程当中遇到了一个问题, 就是使用脚本 stop 进程的时候, 进程会变成僵尸进程(Zombies), 而不是正常中止.docker

但若是不使用 nohup, 直接在前台运行, 而后在另外一个终端中关闭, 是会关闭的.bash

这个问题困扰了我好久, 直到看到 stackoverflow 上的 相似问题.ide

这是在评论中发现的, 有时候豁然开朗就在一瞬间,工具

If you're running the process (even if you've called wait finally) inside the docker container with pid:1, it will also lead to a zombie. github.com/krallin/tini will be helpful in this case. – McKelvin Mar 8 '17 at 11:34单元测试

只要在 docker-compose 中设置 init 为 true 就好了, 相似这样:测试

version: "3.7"
services:
 web:
 image: alpine:latest
 init: true
复制代码

这会在 docker 容器内运行一个 init 来转发信号, 默认的 init 程序就是上面提到的 Tini.

这是在使用 容器开发 时遇到的问题.

总结

启动脚本是一个很是方便的工具, 用于管理进程的启动和中止.

当前部分的代码

做为版本 v0.13.0

相关文章
相关标签/搜索