帅气猫咪的 Go 语言之旅

13使用 Go 添加启动脚本

2019-11-05  本文已影响0人  刷漆猫咪

简介

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

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

实践

直接上脚本了:

#!/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

用法如下:

困惑

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

但如果不使用 nohup, 直接在前台运行, 然后在另一个终端中关闭, 是会关闭的.

这个问题困扰了我很久, 直到看到 stackoverflow 上的
类似问题.

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

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

上一篇下一篇

猜你喜欢

热点阅读