官术网_书友最值得收藏!

  • DevOps with Kubernetes
  • Hideto Saito Hui Chuan Chloe Lee Cheng Yang Wu
  • 418字
  • 2021-07-02 13:41:49

Writing your first Dockerfile

A Dockerfile consists of a series of text instructions to guide the Docker daemon to form an image, and a Dockerfile must start with the FROM directive. For example, we may have an image built from the following one-liner:

docker commit $(                         \
docker start $( \
docker create alpine /bin/sh -c \
"echo My custom build > /etc/motd" \
))

This roughly equates to the following Dockerfile:

FROM alpine
RUN echo "My custom build" > /etc/motd

Obviously, building with a Dockerfile is much more concise and precise.

The docker build [OPTIONS] [CONTEXT] command is the only command associated with building tasks. A context can be a local path, URL, or stdin, which denotes the location of the Dockerfile. Once a build is triggered, the Dockerfile, alongside everything under the context, will be sent to the Docker daemon beforehand and then the daemon will start to execute instructions in the Dockerfile sequentially. Every execution of the instructions results in a new cache layer, and the ensuing instruction is executed at the new cache layer in the cascade. Since the context will be sent somewhere that isn't guaranteed to be a local path, and sending too many irrelevant files takes time, it's a good practice to put the Dockerfile, code, necessary files, and a .dockerignore file in an empty folder to make sure the resultant image contains only the desired files.

The .dockerignore file is a list indicating which files under the same directory can be ignored at build time. It typically looks as follows:

$ cat .dockerignore
# ignore .dockerignore, .git
.dockerignore
.git
# exclude all *.tmp files and vim swp file recursively
**/*.tmp
**/[._]*.s[a-w][a-z]
# exclude all markdown files except README*.md
!README*.md

Generally, docker build will try to locate a file named Dockerfile under the context to start a build. Sometimes, however, we may want to give it another name, which we can do using the -f (--file) flag. Another useful flag, -t (--tag), is able to give an image one or more repository tags after an image is built. Let's say we want to build a Dockerfile named builder.dck under ./deploy and label it with the current date and the latest tag. The command to do this is as follows:

## We can assign the image with more than one tag within a build command
$ docker build -f deploy/builder.dck \
-t my-reg.com/prod/teabreaker:$(date +"%g%m%d") \
-t my-reg.com/prod/teabreaker:latest .
主站蜘蛛池模板: 偏关县| 沭阳县| 晋宁县| 上虞市| 宣威市| 紫云| 新沂市| 克拉玛依市| 大港区| 丰原市| 讷河市| 始兴县| 许昌市| 枣阳市| 合水县| 广灵县| 东宁县| 杭锦旗| 兴国县| 桃江县| 安庆市| 汉源县| 海盐县| 哈巴河县| 巴彦淖尔市| 北票市| 沁源县| 永福县| 江阴市| 曲水县| 山东省| 二手房| 南郑县| 祁门县| 定边县| 福鼎市| 万源市| 无锡市| 镇平县| 莒南县| 昌吉市|