ランサーズ(Lancers)エンジニアブログ > DevOps > Amazon Linux再起動時にUnicornを自動的に起動させる方法

Amazon Linux再起動時にUnicornを自動的に起動させる方法

ota|2017年12月20日
DevOps

ランサーズ Advent Calendar 2017の20日目を担当します、ota(@purratto)です。
今回はAmazon Linux再起動時にUnicornを自動的に起動させる方法を解説します。

実装方法

Unicornを自動的に起動させたいサーバ内に /etc/init.d/unicorn を作成し、下記のように編集します。

#!/bin/sh

#chkconfig:2345 84 16
#description:unicorn shell

. /etc/rc.d/init.d/functions

NAME="Unicorn"
ENV="hoge_env"
ROOT_DIR="/var/www/hoge_dir/current/"
PID_FILE="/var/www/hoge_dir/shared/tmp/pids/unicorn.pid"
PS_PID=$(ps -aef | grep master | grep unicorn | awk '{print $2}')
CONF="${ROOT_DIR}config/unicorn/${ENV}.rb"

start()
{
  PS_PID=$(ps -aef | grep master | grep unicorn | awk '{print $2}')
  if [[ ! -z ${PS_PID} ]] ; then
    echo "${NAME} already started"
    exit 0
  fi
  echo -n "start ${NAME} : "
  daemon $(su -l hoge_user -c "(cd ${ROOT_DIR} && RAILS_ENV=${ENV} /usr/local/rbenv/shims/bundle exec unicorn -c ${CONF} -E ${ENV} -D )")
  echo
}

stop()
{
  if [[ -z ${PS_PID} ]]; then
    echo "${NAME} not started"
    exit 1
  fi

  echo -n "stop ${NAME} : "
  daemon $(kill ${PS_PID})
  echo
  rm -f ${PID_FILE}

  while :
  do
    PS_PID=$(ps -aef | grep master | grep unicorn | awk '{print $2}')
    if [[ -z "${PS_PID}" ]]; then
      break
    fi
    usleep 100000
  done
}

status()
{
  if [[ -z ${PS_PID} ]]; then
    echo "${NAME} is stop"
  else
    echo "${NAME} is running"
  fi
}

restart()
{
  if [[ -z ${PS_PID} ]]; then
    echo "${NAME} not started"
  else
    echo -n "stop ${NAME} : "
    daemon $(kill ${PS_PID})
    echo
    rm -f ${PID_FILE}

    while :
    do
      PS_PID=$(ps -aef | grep master | grep unicorn | awk '{print $2}')
      if [[ -z ${PS_PID} ]]; then
        break
      fi
      usleep 100000
    done
  fi

  start
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    restart
    ;;
  status)
    status
    ;;
  *)
    echo "Syntax Error: release [start|stop|restart|status]"
    ;;
esac

下記のコマンドを実行します。

$ chkconfig –add unicorn
$ chkconfig unicorn on
$ chmod 755 /etc/init.d/unicorn

以上です。参考になれば幸いです。