1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Docker】Dockerfile 内でスクリプトを作成・定義する【entrypoint.sh など】

Last updated at Posted at 2025-03-18

Docker のイメージをビルドする際、通常はローカルにあるスクリプト・ファイルを COPY でイメージにコピーするのが基本です。

しかし、Dockerfile 内でスクリプトを作成したいことが、まれによくあります。

「dockerfile内 スクリプト 作成」でググっても、ドンピシャのタイトルの記事がなかったので、自分のググラビリティとして。

TL; DR (今北産業)

  1. COPY 指示子で、ヒアドキュメント(heredoc)を使ってファイルを作成する

  2. 使用例:

    Dockerfile
    # =============================================================================
    #  ビルド ステージ
    # =============================================================================
    FROM alpine
    
    WORKDIR /app
    RUN apt upgrade --no-cache
    
    COPY --chmod=755 <<EOL /app/entrypoint.sh
    #!/bin/sh
    set -e
    
    echo "Hello, world"
    EOL
    
    ENTRYPOINT [ "/app/entrypoint.sh" ]
    

【注意】上記の場合、PID1 は /app/entrypoint.sh になり echo はサブ・プロセス(子プロセス)になります。

つまり、この場合、コンテナを終了しても SIGINT などの終了シグナルは echo に渡されません

この例では、すぐに実行終了するので特に問題はないのですが echo の代わりに Web サーバーなどサービス系の常駐するアプリの場合には特に注意が必要です。

Ctrl+C しても graceful shutdown(後処理を済ませて安全にアプリを停止)してくれません。

docker run --init myimage:latest--init オプションを付けて実行するか、シェルのスクリプト内で exec を使います。

- echo "Hello, world"
+ exec /bin/echo "Hello, world"

参考文献/あわせて読みたい

1
1
1

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?