使用 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

相關文章
相關標籤/搜索