【Docker】Dockerfile 最佳實踐-ENV
參考教程:https://docs.docker.com/develop/develop-images/dockerfile_best-practices/
環境
- virtual box 6.1
- centos 7.8
- docker 19.03
ENV
To make new software easier to run, you can use ENV
to update the PATH
environment variable for the software your container installs. For example, ENV PATH=/usr/local/nginx/bin:$PATH
ensures that CMD ["nginx"]
為了使新軟體易於執行,您可以使用 ENV
來更新容器安裝的軟體的 PATH
環境變數。例如,ENV PATH=/usr/local/nginx/bin:$PATH
確保 CMD ["nginx"]
正常工作。
The ENV
instruction is also useful for providing required environment variables specific to services you wish to containerize, such as Postgres’s PGDATA
.
ENV
指令還可用於提供特定於您希望容器化的服務的必需環境變數,例如 Postgres 的 PGDATA
Lastly, ENV
can also be used to set commonly used version numbers so that version bumps are easier to maintain, as seen in the following example:
最後,ENV
也可以用來設定常用的版本號,以便更容易維護版本,如以下示例所示:
ENV PG_MAJOR=9.3 ENV PG_VERSION=9.3.4 RUN curl -SL https://example.com/postgres-$PG_VERSION.tar.xz | tar -xJC /usr/src/postgress && … ENV PATH=/usr/local/postgres-$PG_MAJOR/bin:$PATH
Similar to having constant variables in a program (as opposed to hard-coding values), this approach lets you change a single ENV
instruction to auto-magically bump the version of the software in your container.
類似於在程式中具有變數(與硬編碼值相反),這種方法使您可以更改單個 ENV
指令以自動神奇地修改容器中軟體的版本。
Each ENV
line creates a new intermediate layer, just like RUN
commands. This means that even if you unset the environment variable in a future layer, it still persists in this layer and its value can’t be dumped. You can test this by creating a Dockerfile like the following, and then building it.
每條 ENV
行都會建立一個新的中間層,就像 RUN
命令一樣。這意味著,即使您在以後的層中取消設定環境變數,它也仍然保留在該層中,並且其值也無法轉儲。您可以通過建立如下所示的 Dockerfile,然後對其進行構建來進行測試。
FROM alpine
ENV ADMIN_USER="mark"
RUN echo $ADMIN_USER > ./mark
RUN unset ADMIN_USER
$ docker run --rm test sh -c 'echo $ADMIN_USER'
mark
To prevent this, and really unset the environment variable, use a RUN
command with shell commands, to set, use, and unset the variable all in a single layer. You can separate your commands with ;
or &&
. If you use the second method, and one of the commands fails, the docker build
also fails. This is usually a good idea. Using \
as a line continuation character for Linux Dockerfiles improves readability. You could also put all of the commands into a shell script and have the RUN
command just run that shell script.
為了避免這種情況,並真正取消設定環境變數,請在外殼程式中使用帶有外殼命令的 RUN
命令來設定,使用和取消設定該變數。您可以使用 ;
或 &&
分隔命令。如果您使用第二種方法,並且其中一個命令失敗,則 docker build
也會失敗。這通常是個好主意。將 \
用作 Linux Dockerfiles 的行繼續符可提高可讀性。您也可以將所有命令放入一個 shell 指令碼中,並讓 RUN
命令執行該 shell 指令碼。
FROM alpine
RUN export ADMIN_USER="mark" \
&& echo $ADMIN_USER > ./mark \
&& unset ADMIN_USER
CMD sh
$ docker run --rm test sh -c 'echo $ADMIN_USER'
總結
介紹了 Dockerfile 的 ENV 指令的最佳實踐。