9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

dockerのコマンドが毎回めんどくさいのでbashテンプレ化

Last updated at Posted at 2023-02-01

まえがき

毎回イメージ名打ち込んだり面倒でスクリプト作ってたので、テンプレに起こした
aliasやmakeでもよかったけど、都度ちょいちょい変わるのでリポジトリ別に設置できるよう

(2023/02/06) 追記 docker-compose用書いた
docker-composeのコマンドが毎回めんどくさいのでbashテンプレ化 - Qiita

注意点

  • 前提として私用開発用(雑)、自己責任で煮るなり焼くなりどうぞ
    • 肥大化する場合は別の手段を考える事を推奨
  • 一階層掘った場所を想定(ex $ ./scripts/ctl)
  • # executeのところで雑にコールしてるので脆弱性に繋がる可能性あり
    • 定義とusageで2箇所の編集に留めたかった
    • 定義済関数を呼び出せるので、心配ならcaseにして呼び出しに制限を
    • 露出しないよう除外など推奨(ciでrm、dockerignore/gitignore)

script

scripts/ctl
#!/bin/bash
SCRIPT_DIR=`dirname "${0}"`
SCRIPT_NAME=`basename "${0}"`

# cd to exec dir
cd "${SCRIPT_DIR}/../"
IMAGE_NAME=`basename "$(pwd)"`
VERSION='latest'
IMAGE="${IMAGE_NAME}:${VERSION}"


# --------------------------------------------------
# args
CTL_CMD="${1}"
shift

while getopts h OPT
do
  case $OPT in
     h) OPT_HELP=1;;
     *) ;;
  esac
  shift
done

REST_ARGS="${@}"


# --------------------------------------------------
# functions
usage() {
  cat << EOS

Usage: ${SCRIPT_DIR}/${SCRIPT_NAME} COMMAND [REST_ARGS]

Options:
  -h Print usage

Commands:
  build   `type _build | grep '^ '`
  run     `type _run   | grep '^ '`
  exec    `type _exec  | grep '^ '`
  stop    `type _stop  | grep '^ '`

EOS
  exit 1
}


_build() {
  docker build -t "${IMAGE}" . ${REST_ARGS}
}

_run() {
  docker run -it "${IMAGE}" ${REST_ARGS}
}

_psq() {
  docker ps -q --filter "ancestor=${IMAGE}"
}

_exec() {
  _psq | head -1 | xargs -I{} docker exec -i "{}" ${REST_ARGS}
}

_stop() {
  _psq | xargs docker stop
}


__main() {
  if [ "${OPT_HELP:-0}" -eq "1" ] || [ -z "${CTL_CMD}" ]; then
    usage
  fi

  type "_${CTL_CMD}" > /dev/null 2>&1

  if [ "${?}" -eq "0" ]; then
    # execute
    _${CTL_CMD}
  else
    echo "-${0}: ${SCRIPT_NAME}: ${CTL_CMD} command not found" 1>&2
    usage
  fi
}

__main

ex. usage

$ ./scripts/ctl

Usage: ./scripts/ctl COMMAND [REST_ARGS]

Options:
  -h Print usage

Commands:
  build       docker build -t "${IMAGE}" . ${REST_ARGS}
  run         docker run -it "${IMAGE}" ${REST_ARGS}
  exec        _psq | head -1 | xargs -I{} docker exec -i "{}" ${REST_ARGS}
  stop        _psq | xargs docker stop

$ ./scripts/ctl run echo 'Lorem ipsum'
Lorem ipsum

あとがき

突貫なので不都合出てきたら修正するかも。
もっと良い感じにできそうだったら教えて頂けますと幸いです。

9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?