1. 程式人生 > 實用技巧 >【Docker】Dockerfile 最佳實踐-ENTRYPOINT

【Docker】Dockerfile 最佳實踐-ENTRYPOINT

參考教程:https://docs.docker.com/develop/develop-images/dockerfile_best-practices/

環境

  1. virtual box 6.1
  2. centos 7.8
  3. docker 19.03

ENTRYPOINT

The best use for ENTRYPOINT is to set the image’s main command, allowing that image to be run as though it was that command (and then use CMD as the default flags).

ENTRYPOINT

的最佳用途是設定映象的主命令,使該映象像該命令一樣執行(然後使用 CMD 作為預設標誌)。

Let’s start with an example of an image for the command line tool s3cmd:

讓我們從命令列工具 s3cmd 的映象示例開始:

ENTRYPOINT ["s3cmd"]
CMD ["--help"]

Now the image can be run like this to show the command’s help:

現在可以像這樣執行映象以顯示命令的幫助:

$ docker run s3cmd

Or using the right parameters to execute a command:

或使用正確的引數執行命令:

$ docker run s3cmd ls s3://mybucket

This is useful because the image name can double as a reference to the binary as shown in the command above.

這很有用,因為映象名稱可以用作對二進位制檔案的引用,如上面的命令所示。

The ENTRYPOINT instruction can also be used in combination with a helper script, allowing it to function in a similar way to the command above, even when starting the tool may require more than one step.

ENTRYPOINT 指令也可以與輔助指令碼結合使用,即使啟動該工具可能需要一個以上的步驟,也可以使其與上述命令類似地工作。

For example, the Postgres Official Image uses the following script as its ENTRYPOINT:

例如,Postgres Official Image 使用以下指令碼作為其 ENTRYPOINT

#!/bin/bash
set -e

if [ "$1" = 'postgres' ]; then
    chown -R postgres "$PGDATA"

    if [ -z "$(ls -A "$PGDATA")" ]; then
        gosu postgres initdb
    fi

    exec gosu postgres "$@"
fi

exec "$@"

Configure app as PID 1
將應用程式配置為PID 1

This script uses the exec Bash command so that the final running application becomes the container’s PID 1. This allows the application to receive any Unix signals sent to the container. For more, see the ENTRYPOINT reference.
該指令碼使用 exec Bash 命令,以便最終執行的應用程式成為容器的 PID1。這使該應用程式可以接收發送到該容器的所有 Unix 訊號。有關更多資訊,請參見 ENTRYPOINT 參考。

The helper script is copied into the container and run via ENTRYPOINT on container start:

將幫助程式指令碼複製到容器中,並在容器啟動時通過 ENTRYPOINT 執行:

COPY ./docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["postgres"]

This script allows the user to interact with Postgres in several ways.

該指令碼允許使用者以多種方式與 Postgres 進行互動。

It can simply start Postgres:

它可以簡單地啟動 Postgres:

$ docker run postgres

Or, it can be used to run Postgres and pass parameters to the server:

或者,它可以用於執行 Postgres 並將引數傳遞給伺服器:

$ docker run postgres postgres --help

Lastly, it could also be used to start a totally different tool, such as Bash:
最後,它也可以用於啟動一個完全不同的工具,例如 Bash:

$ docker run --rm -it postgres bash

總結

介紹了 Dockerfile 的 ENTRYPOINT 指令的最佳實踐。