Dockerfile编写最佳实践指南

最近一段时间弄了下Dockerfile,实践中也发现了不少问题,总结如下:

1. Java环境变量不生效的问题:

启动容器不同于系统完整启动流程,当容器运行后不会执行source /etc/profile命令,即使在/etc/profile添加环境变量也不会生效,可以使用ENV参数在Dockerfile中定义,也可以使用entrypoint在脚本里执行添加环境变量的命令。

Dockerfile不是shell脚本,而是定制rootfs的脚本。它并不是在运行时运行的,而是在构建时运行的。

2. 容器设置时区

#设置一个时区的环境变量

ENV TZ "Asia/Shanghai"

手动更改:

sed -i 's%ZONE="UTC"%ZONE="Asia/Shanghai"%g' /etc/sysconfig/clock && ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

3. 容器中无法看到非root用户运行程序的PID

参考:docker容器中root用户无法查看其它用户运行进程的PID

4. Dockerfile中chown不生效的问题

Here are 3 different but possible solutions:

  1. Using a dockerfile and doing a chown before mounting the volume.

  2. USER ROOT command in dockerfile before you do a chown.

  3. Use --cap-add flag.

参考:

An important point from that article above: "[When VOLUME is specified after a RUN command that modifies the volume], docker is clever enough to copy any files that exist in the image under the volume mount into the volume and set the ownership correctly. This won’t happen if you specify a host directory for the volume (so that host files aren’t accidentally overwritten).

https://stackoverflow.com/questions/26145351/why-doesnt-chown-work-in-dockerfile

5. 打Dockerfile时yum源域名无法解析

很郁闷的一个问题,最后换了台机器打Dockerfile就好了,不知道什么原因。

6. 打Dockerfile时提示glibc包冲突

使用公司内部源下载时glibc包文件版本有冲突,最后更换成阿里yum源下载gcc后解决

7. 容器添加cron定时任务

将定时任务写到文件里,打Dockerfile时添加

COPY config/root /var/spool/cron/root

chmod 600 /var/spool/cron/root

Dockerfile缩写原则:

1.减少分层:把同一个任务的命令放到RUN下,多条命令应该用 && 连接,用 \ 换行,并且在最后要打扫干净所使用的环境

2.合理分层:将具有不同变量频繁程度的层进行拆分,让稳定的部分在基础,更容易变量的部分在表层,使得资源可以重复利用,以增加构建和部署的速度。

3.使用.dockerignore文件来过滤不必要的内容。.dockerignore文件应该放置于上下文顶级目录下


参考:

Docker镜像构建及Dockerfile

如何编写最佳的Dockerfile

Best practices for writing Dockerfiles


For example:

FROM centos:centos6.6

MAINTAINER anzhihe "anzhihe@chegva.com"

RUN yum install -y wget \
    && /bin/rm -f /etc/yum.repos.d/* \
    && wget -nv -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo \
    ......
    && yum clean all
    
#ENV init
ENV JAVA_HOME=/usr/local/jdk \
    PATH=$PATH:$JAVA_HOME/bin:/home/anzhihe/opshell/:/sbin:/bin:/usr/sbin:/usr/bin \
    TZ="Asia/Shanghai"

# supervisord config file & cron
COPY config/supervisord.conf /etc/supervisord.conf
COPY config/root /var/spool/cron/root

# chmod  & clean yum cache
RUN chown -R anzhihe.anzhihe /home /tmp \
    && chmod 600 /var/spool/cron/root \
    && find /var/cache/yum/ -type f |xargs rm -f

# 设置外部挂载目录
VOLUME ["data/www/","/data/logs/"]

# 导出端口
EXPOSE 22 8080

# 启动执行脚本
CMD ["/usr/bin/supervisord"]

如何编写最佳的Dockerfile

译者按: Dockerfile的语法非常简单,然而如何加快镜像构建速度,如何减少Docker镜像的大小却不是那么直观,需要积累实践经验。这篇博客可以帮助你快速掌握编写Dockerfile的技巧。

原文: How to write excellent Dockerfiles

译者: Fundebug

为了保证可读性,本文采用意译而非直译。另外,本文版权归原作者所有,翻译仅用于学习

我已经使用Docker有一段时间了,其中编写Dockerfile是非常重要的一部分工作。在这篇博客中,我打算分享一些建议,帮助大家编写更好的Dockerfile。

目标:

  • 更快的构建速度

  • 更小的Docker镜像大小

  • 更少的Docker镜像层

  • 充分利用镜像缓存

  • 增加Dockerfile可读性

  • 让Docker容器使用起来更简单

总结

  • 编写.dockerignore文件

  • 容器只运行单个应用

  • 将多个RUN指令合并为一个

  • 基础镜像的标签不要用latest

  • 每个RUN指令后删除多余文件

  • 选择合适的基础镜像(alpine版本最好)

  • 设置WORKDIR和CMD

  • 使用ENTRYPOINT (可选)

  • 在entrypoint脚本中使用exec

  • COPY与ADD优先使用前者

  • 合理调整COPY与RUN的顺序

  • 设置默认的环境变量,映射端口和数据卷

  • 使用LABEL设置镜像元数据

  • 添加HEALTHCHECK

示例

示例Dockerfile犯了几乎所有的错(当然我是故意的)。接下来,我会一步步优化它。假设我们需要使用Docker运行一个Node.js应用,下面就是它的Dockerfile(CMD指令太复杂了,所以我简化了,它是错误的,仅供参考)。


FROM ubuntu

ADD . /app

RUN apt-get update  
RUN apt-get upgrade -y  
RUN apt-get install -y nodejs ssh mysql  
RUN cd /app && npm install

# this should start three processes, mysql and ssh
# in the background and node app in foreground
# isn't it beautifully terrible? <3
CMD mysql & sshd & npm start

构建镜像:


docker build -t wtf .

1. 编写.dockerignore文件

构建镜像时,Docker需要先准备context ,将所有需要的文件收集到进程中。默认的context包含Dockerfile目录中的所有文件,但是实际上,我们并不需要.git目录,node_modules目录等内容.dockerignore 的作用和语法类似于 .gitignore,可以忽略一些不需要的文件,这样可以有效加快镜像构建时间,同时减少Docker镜像的大小。示例如下:


.git/
node_modules/

2. 容器只运行单个应用

从技术角度讲,你可以在Docker容器中运行多个进程。你可以将数据库,前端,后端,ssh,supervisor都运行在同一个Docker容器中。但是,这会让你非常痛苦:

  • 非常长的构建时间(修改前端之后,整个后端也需要重新构建)

  • 非常大的镜像大小

  • 多个应用的日志难以处理(不能直接使用stdout,否则多个应用的日志会混合到一起)

  • 横向扩展时非常浪费资源(不同的应用需要运行的容器数并不相同)

  • 僵尸进程问题 - 你需要选择合适的init进程

因此,我建议大家为每个应用构建单独的Docker镜像,然后使用 Docker Compose 运行多个Docker容器。

现在,我从Dockerfile中删除一些不需要的安装包,另外,SSH可以用docker exec替代。示例如下:


FROM ubuntu

ADD . /app

RUN apt-get update  
RUN apt-get upgrade -y

# we should remove ssh and mysql, and use
# separate container for database
RUN apt-get install -y nodejs  # ssh mysql  
RUN cd /app && npm install

CMD npm start

3. 将多个RUN指令合并为一个

Docker镜像是分层的,下面这些知识点非常重要:

  • Dockerfile中的每个指令都会创建一个新的镜像层。

  • 镜像层将被缓存和复用

  • 当Dockerfile的指令修改了,复制的文件变化了,或者构建镜像时指定的变量不同了,对应的镜像层缓存就会失效

  • 某一层的镜像缓存失效之后,它之后的镜像层缓存都会失效

  • 镜像层是不可变的,如果我们再某一层中添加一个文件,然后在下一层中删除它,则镜像中依然会包含该文件(只是这个文件在Docker容器中不可见了)。

Docker镜像类似于洋葱。它们都有很多层。为了修改内层,则需要将外面的层都删掉。记住这一点的话,其他内容就很好理解了。

现在,我们将所有的RUN指令合并为一个。同时把apt-get upgrade删除,因为它会使得镜像构建非常不确定(我们只需要依赖基础镜像的更新就好了)


FROM ubuntu

ADD . /app

RUN apt-get update \  
   && apt-get install -y nodejs \
   && cd /app \
   && npm install

CMD npm start

记住一点,我们只能将变化频率一样的指令合并在一起。将node.js安装与npm模块安装放在一起的话,则每次修改源代码,都需要重新安装node.js,这显然不合适。因此,正确的写法是这样的:


FROM ubuntu

RUN apt-get update && apt-get install -y nodejs  
ADD . /app  
RUN cd /app && npm install

CMD npm start

4. 基础镜像的标签不要用latest

当镜像没有指定标签时,将默认使用latest 标签。因此, FROM ubuntu 指令等同于FROM ubuntu:latest。当时,当镜像更新时,latest标签会指向不同的镜像,这时构建镜像有可能失败。如果你的确需要使用最新版的基础镜像,可以使用latest标签,否则的话,最好指定确定的镜像标签。

示例Dockerfile应该使用16.04作为标签。


FROM ubuntu:16.04  # it's that easy!

RUN apt-get update && apt-get install -y nodejs  
ADD . /app  
RUN cd /app && npm install

CMD npm start

5. 每个RUN指令后删除多余文件

假设我们更新了apt-get源,下载,解压并安装了一些软件包,它们都保存在/var/lib/apt/lists/目录中。但是,运行应用时Docker镜像中并不需要这些文件。我们最好将它们删除,因为它会使Docker镜像变大。

示例Dockerfile中,我们可以删除/var/lib/apt/lists/目录中的文件(它们是由apt-get update生成的)。


FROM ubuntu:16.04

RUN apt-get update \  
   && apt-get install -y nodejs \
   # added lines
   && rm -rf /var/lib/apt/lists/*

ADD . /app  
RUN cd /app && npm install

CMD npm start

6. 选择合适的基础镜像(alpine版本最好)

在示例中,我们选择了ubuntu作为基础镜像。但是我们只需要运行node程序,有必要使用一个通用的基础镜像吗?node镜像应该是更好的选择。


FROM node

ADD . /app  
# we don't need to install node
# anymore and use apt-get
RUN cd /app && npm install

CMD npm start

更好的选择是alpine版本的node镜像。alpine是一个极小化的Linux发行版,只有4MB,这让它非常适合作为基础镜像。


FROM node:7-alpine

ADD . /app  
RUN cd /app && npm install

CMD npm start

apk是Alpine的包管理工具。它与apt-get有些不同,但是非常容易上手。另外,它还有一些非常有用的特性,比如no-cache--virtual选项,它们都可以帮助我们减少镜像的大小。

7. 设置WORKDIR和 CMD

WORKDIR指令可以设置默认目录,也就是运行RUN / CMD / ENTRYPOINT指令的地方。

CMD指令可以设置容器创建是执行的默认命令。另外,你应该将命令写在一个数组中,数组中每个元素为命令的每个单词(参考官方文档)。


FROM node:7-alpine

WORKDIR /app  
ADD . /app  
RUN npm install

CMD ["npm", "start"]

8. 使用ENTRYPOINT (可选)

ENTRYPOINT指令并不是必须的,因为它会增加复杂度。ENTRYPOINT是一个脚本,它会默认执行,并且将指定的命令错误其参数。它通常用于构建可执行的Docker镜像。entrypoint.sh如下:


#!/usr/bin/env sh
# $0 is a script name,
# $1, $2, $3 etc are passed arguments
# $1 is our command
CMD=$1

case "$CMD" in  
 "dev" )
   npm install
   export NODE_ENV=development
   exec npm run dev
   ;;

 "start" )
   # we can modify files here, using ENV variables passed in
   # "docker create" command. It can't be done during build process.
   echo "db: $DATABASE_ADDRESS" >> /app/config.yml
   export NODE_ENV=production
   exec npm start
   ;;

  * )
   # Run custom command. Thanks to this line we can still use
   # "docker run our_image /bin/bash" and it will work
   exec $CMD ${@:2}
   ;;
esac

示例Dockerfile:


FROM node:7-alpine

WORKDIR /app  
ADD . /app  
RUN npm install

ENTRYPOINT ["./entrypoint.sh"]  
CMD ["start"]

可以使用如下命令运行该镜像:


# 运行开发版本
docker run our-app dev

# 运行生产版本
docker run our-app start

# 运行bash
docker run -it our-app /bin/bash

9. 在entrypoint脚本中使用exec

在前文的entrypoint脚本中,我使用了exec命令运行node应用。不使用exec的话,我们则不能顺利地关闭容器,因为SIGTERM信号会被bash脚本进程吞没。exec命令启动的进程可以取代脚本进程,因此所有的信号都会正常工作。

10. COPY与ADD优先使用前者

COPY指令非常简单,仅用于将文件拷贝到镜像中。ADD相对来讲复杂一些,可以用于下载远程文件以及解压压缩包(参考官方文档)。


FROM node:7-alpine

WORKDIR /app

COPY . /app  
RUN npm install

ENTRYPOINT ["./entrypoint.sh"]  
CMD ["start"]

11. 合理调整COPY与RUN的顺序

我们应该把变化最少的部分放在Dockerfile的前面,这样可以充分利用镜像缓存。

示例中,源代码会经常变化,则每次构建镜像时都需要重新安装NPM模块,这显然不是我们希望看到的。因此我们可以先拷贝package.json,然后安装NPM模块,最后才拷贝其余的源代码。这样的话,即使源代码变化,也不需要重新安装NPM模块。


FROM node:7-alpine

WORKDIR /app

COPY package.json /app  
RUN npm install  
COPY . /app

ENTRYPOINT ["./entrypoint.sh"]  
CMD ["start"]

12. 设置默认的环境变量,映射端口和数据卷

运行Docker容器时很可能需要一些环境变量。在Dockerfile设置默认的环境变量是一种很好的方式。另外,我们应该在Dockerfile中设置映射端口和数据卷。示例如下:


FROM node:7-alpine

ENV PROJECT_DIR=/app

WORKDIR $PROJECT_DIR

COPY package.json $PROJECT_DIR  
RUN npm install  
COPY . $PROJECT_DIR

ENV MEDIA_DIR=/media \  
   NODE_ENV=production \
   APP_PORT=3000

VOLUME $MEDIA_DIR  
EXPOSE $APP_PORT

ENTRYPOINT ["./entrypoint.sh"]  
CMD ["start"]

ENV指令指定的环境变量在容器中可以使用。如果你只是需要指定构建镜像时的变量,你可以使用ARG指令。

13. 使用LABEL设置镜像元数据

使用LABEL指令,可以为镜像设置元数据,例如镜像创建者或者镜像说明。旧版的Dockerfile语法使用MAINTAINER指令指定镜像创建者,但是它已经被弃用了。有时,一些外部程序需要用到镜像的元数据,例如nvidia-docker需要用到com.nvidia.volumes.needed。示例如下:


FROM node:7-alpine  
LABEL maintainer "jakub.skalecki@example.com"  
...

14. 添加HEALTHCHECK

运行容器时,可以指定--restart always选项。这样的话,容器崩溃时,Docker守护进程(docker daemon)会重启容器。对于需要长时间运行的容器,这个选项非常有用。但是,如果容器的确在运行,但是不可(陷入死循环,配置错误)用怎么办?使用HEALTHCHECK指令可以让Docker周期性的检查容器的健康状况。我们只需要指定一个命令,如果一切正常的话返回0,否则返回1。对HEALTHCHECK感兴趣的话,可以参考这篇博客。示例如下:


FROM node:7-alpine  
LABEL maintainer "jakub.skalecki@example.com"

ENV PROJECT_DIR=/app  
WORKDIR $PROJECT_DIR

COPY package.json $PROJECT_DIR  
RUN npm install  
COPY . $PROJECT_DIR

ENV MEDIA_DIR=/media \  
   NODE_ENV=production \
   APP_PORT=3000

VOLUME $MEDIA_DIR  
EXPOSE $APP_PORT  
HEALTHCHECK CMD curl --fail http://localhost:$APP_PORT || exit 1

ENTRYPOINT ["./entrypoint.sh"]  
CMD ["start"]

当请求失败时,curl --fail 命令返回非0状态。转载自:https://blog.fundebug.com/2017/05/15/write-excellent-dockerfile/



Best practices for writing Dockerfiles

Docker can build images automatically by reading the instructions from a Dockerfile, a text file that contains all the commands, in order, needed to build a given image. Dockerfiles adhere to a specific format and use a specific set of instructions. You can learn the basics on the Dockerfile Reference page. If you’re new to writing Dockerfiles, you should start there.

This document covers the best practices and methods recommended by Docker, Inc. and the Docker community for building efficient images. To see many of these practices and recommendations in action, check out the Dockerfile forbuildpack-deps.

Note: for more detailed explanations of any of the Dockerfile commands mentioned here, visit the Dockerfile Reference page.

General guidelines and recommendations

Containers should be ephemeral

The container produced by the image your Dockerfile defines should be as ephemeral as possible. By “ephemeral,” we mean that it can be stopped and destroyed and a new one built and put in place with an absolute minimum of set-up and configuration. You may want to take a look at the Processes section of the 12 Factor app methodology to get a feel for the motivations of running containers in such a stateless fashion.

Use a .dockerignore file

The current working directory where you are located when you issue a docker build command is called the build context, and the Dockerfile must be somewhere within this build context. By default, it is assumed to be in the current directory, but you can specify a different location by using the -f flag. Regardless of where the Dockerfile actually lives, all of the recursive contents of files and directories in the current directory are sent to the Docker daemon as the build context. Inadvertently including files that are not necessary for building the image results in a larger build context and larger image size. These in turn can increase build time, time to pull and push the image, and the runtime size of containers. To see how big your build context is, look for a message like the following, when you build your Dockerfile.

Sending build context to Docker daemon  187.8MB

To exclude files which are not relevant to the build, without restructuring your source repository, use a .dockerignorefile. This file supports exclusion patterns similar to .gitignore files. For information on creating one, see the .dockerignore file. In addition to using a .dockerignore file, check out the information below on multi-stage builds.

Use multi-stage builds

If you use Docker 17.05 or higher, you can use multi-stage builds to drastically reduce the size of your final image, without the need to jump through hoops to reduce the number of intermediate layers or remove intermediate files during the build.

Avoid installing unnecessary packages

In order to reduce complexity, dependencies, file sizes, and build times, you should avoid installing extra or unnecessary packages just because they might be “nice to have.” For example, you don’t need to include a text editor in a database image.

Each container should have only one concern

Decoupling applications into multiple containers makes it much easier to scale horizontally and reuse containers. For instance, a web application stack might consist of three separate containers, each with its own unique image, to manage the web application, database, and an in-memory cache in a decoupled manner.

You may have heard that there should be “one process per container”. While this mantra has good intentions, it is not necessarily true that there should be only one operating system process per container. In addition to the fact that containers can now be spawned with an init process, some programs might spawn additional processes of their own accord. For instance, Celery can spawn multiple worker processes, or Apache might create a process per request. While “one process per container” is frequently a good rule of thumb, it is not a hard and fast rule. Use your best judgment to keep containers as clean and modular as possible.

If containers depend on each other, you can use Docker container networks to ensure that these containers can communicate.

Minimize the number of layers

Prior to Docker 17.05, and even more, prior to Docker 1.10, it was important to minimize the number of layers in your image. The following improvements have mitigated this need:

  • In Docker 1.10 and higher, only RUNCOPY, and ADD instructions create layers. Other instructions create temporary intermediate images, and no longer directly increase the size of the build.

  • Docker 17.05 and higher add support for multi-stage builds, which allow you to copy only the artifacts you need into the final image. This allows you to include tools and debug information in your intermediate build stages without increasing the size of the final image.

Sort multi-line arguments

Whenever possible, ease later changes by sorting multi-line arguments alphanumerically. This will help you avoid duplication of packages and make the list much easier to update. This also makes PRs a lot easier to read and review. Adding a space before a backslash (\) helps as well.

Here’s an example from the buildpack-deps image:

RUN apt-get update && apt-get install -y \
  bzr \
  cvs \
  git \
  mercurial \
  subversion

Build cache

During the process of building an image Docker will step through the instructions in your Dockerfile executing each in the order specified. As each instruction is examined Docker will look for an existing image in its cache that it can reuse, rather than creating a new (duplicate) image. If you do not want to use the cache at all you can use the --no-cache=trueoption on the docker build command.

However, if you do let Docker use its cache then it is very important to understand when it will, and will not, find a matching image. The basic rules that Docker will follow are outlined below:

  • Starting with a parent image that is already in the cache, the next instruction is compared against all child images derived from that base image to see if one of them was built using the exact same instruction. If not, the cache is invalidated.

  • In most cases simply comparing the instruction in the Dockerfile with one of the child images is sufficient. However, certain instructions require a little more examination and explanation.

  • For the ADD and COPY instructions, the contents of the file(s) in the image are examined and a checksum is calculated for each file. The last-modified and last-accessed times of the file(s) are not considered in these checksums. During the cache lookup, the checksum is compared against the checksum in the existing images. If anything has changed in the file(s), such as the contents and metadata, then the cache is invalidated.

  • Aside from the ADD and COPY commands, cache checking will not look at the files in the container to determine a cache match. For example, when processing a RUN apt-get -y update command the files updated in the container will not be examined to determine if a cache hit exists. In that case just the command string itself will be used to find a match.

Once the cache is invalidated, all subsequent Dockerfile commands will generate new images and the cache will not be used.

The Dockerfile instructions

Below you’ll find recommendations for the best way to write the various instructions available for use in a Dockerfile.

FROM

Dockerfile reference for the FROM instruction

Whenever possible, use current Official Repositories as the basis for your image. We recommend the Debian image since it’s very tightly controlled and kept minimal (currently under 150 mb), while still being a full distribution.

LABEL

Understanding object labels

You can add labels to your image to help organize images by project, record licensing information, to aid in automation, or for other reasons. For each label, add a line beginning with LABEL and with one or more key-value pairs. The following examples show the different acceptable formats. Explanatory comments are included inline.

Note: If your string contains spaces, it must be quoted or the spaces must be escaped. If your string contains inner quote characters ("), escape them as well.

# Set one or more individual labelsLABEL com.example.version="0.0.1-beta"LABEL vendor="ACME Incorporated"LABEL com.example.release-date="2015-02-12"LABEL com.example.version.is-production=""

An image can have more than one label. Prior to Docker 1.10, it was recommended to combine all labels into a single LABEL instruction, to prevent extra layers from being created. This is no longer necessary, but combining labels is still supported.

# Set multiple labels on one lineLABEL com.example.version="0.0.1-beta" com.example.release-date="2015-02-12"

The above can also be written as:

# Set multiple labels at once, using line-continuation characters to break long linesLABEL vendor=ACME\ Incorporated \      com.example.is-beta= \      com.example.is-production="" \      com.example.version="0.0.1-beta" \      com.example.release-date="2015-02-12"

See Understanding object labels for guidelines about acceptable label keys and values. For information about querying labels, refer to the items related to filtering in Managing labels on objects. See also LABEL in the Dockerfile reference.

RUN

Dockerfile reference for the RUN instruction

As always, to make your Dockerfile more readable, understandable, and maintainable, split long or complex RUNstatements on multiple lines separated with backslashes.

APT-GET

Probably the most common use-case for RUN is an application of apt-get. The RUN apt-get command, because it installs packages, has several gotchas to look out for.

You should avoid RUN apt-get upgrade or dist-upgrade, as many of the “essential” packages from the parent images won’t upgrade inside an unprivileged container. If a package contained in the parent image is out-of-date, you should contact its maintainers. If you know there’s a particular package, foo, that needs to be updated, useapt-get install -y foo to update automatically.

Always combine RUN apt-get update with apt-get install in the same RUN statement. For example:

    RUN apt-get update && apt-get install -y \
        package-bar \
        package-baz \
        package-foo

Using apt-get update alone in a RUN statement causes caching issues and subsequent apt-get installinstructions fail. For example, say you have a Dockerfile:

    FROM ubuntu:14.04
    RUN apt-get update
    RUN apt-get install -y curl

After building the image, all layers are in the Docker cache. Suppose you later modify apt-get install by adding extra package:

    FROM ubuntu:14.04
    RUN apt-get update
    RUN apt-get install -y curl nginx

Docker sees the initial and modified instructions as identical and reuses the cache from previous steps. As a result the apt-get update is NOT executed because the build uses the cached version. Because the apt-get update is not run, your build can potentially get an outdated version of the curl and nginx packages.

Using RUN apt-get update && apt-get install -y ensures your Dockerfile installs the latest package versions with no further coding or manual intervention. This technique is known as “cache busting”. You can also achieve cache-busting by specifying a package version. This is known as version pinning, for example:

    RUN apt-get update && apt-get install -y \
        package-bar \
        package-baz \
        package-foo=1.3.*

Version pinning forces the build to retrieve a particular version regardless of what’s in the cache. This technique can also reduce failures due to unanticipated changes in required packages.

Below is a well-formed RUN instruction that demonstrates all the apt-get recommendations.

RUN apt-get update && apt-get install -y \
    aufs-tools \
    automake \
    build-essential \
    curl \
    dpkg-sig \
    libcap-dev \
    libsqlite3-dev \
    mercurial \
    reprepro \
    ruby1.9.1 \
    ruby1.9.1-dev \
    s3cmd=1.1.* \
 && rm -rf /var/lib/apt/lists/*

The s3cmd instructions specifies a version 1.1.*. If the image previously used an older version, specifying the new one causes a cache bust of apt-get update and ensure the installation of the new version. Listing packages on each line can also prevent mistakes in package duplication.

In addition, when you clean up the apt cache by removing /var/lib/apt/lists reduces the image size, since the apt cache is not stored in a layer. Since the RUN statement starts with apt-get update, the package cache will always be refreshed prior to apt-get install.

Note: The official Debian and Ubuntu images automatically run apt-get clean, so explicit invocation is not required.

USING PIPES

Some RUN commands depend on the ability to pipe the output of one command into another, using the pipe character (|), as in the following example:

RUN wget -O - https://some.site | wc -l > /number

Docker executes these commands using the /bin/sh -c interpreter, which only evaluates the exit code of the last operation in the pipe to determine success. In the example above this build step succeeds and produces a new image so long as the wc -l command succeeds, even if the wget command fails.

If you want the command to fail due to an error at any stage in the pipe, prepend set -o pipefail && to ensure that an unexpected error prevents the build from inadvertently succeeding. For example:

RUN set -o pipefail && wget -O - https://some.site | wc -l > /number

Note: Not all shells support the -o pipefail option. In such cases (such as the dash shell, which is the default shell on Debian-based images), consider using the exec form of RUN to explicitly choose a shell that does support the pipefail option. For example:

RUN ["/bin/bash", "-c", "set -o pipefail && wget -O - https://some.site | wc -l > /number"]

CMD

Dockerfile reference for the CMD instruction

The CMD instruction should be used to run the software contained by your image, along with any arguments. CMDshould almost always be used in the form of CMD [“executable”, “param1”, “param2”…]. Thus, if the image is for a service, such as Apache and Rails, you would run something like CMD ["apache2","-DFOREGROUND"]. Indeed, this form of the instruction is recommended for any service-based image.

In most other cases, CMD should be given an interactive shell, such as bash, python and perl. For example, CMD ["perl", "-de0"]CMD ["python"], or CMD [“php”, “-a”]. Using this form means that when you execute something like docker run -it python, you’ll get dropped into a usable shell, ready to go. CMD should rarely be used in the manner of CMD [“param”, “param”] in conjunction with ENTRYPOINT, unless you and your expected users are already quite familiar with how ENTRYPOINT works.

EXPOSE

Dockerfile reference for the EXPOSE instruction

The EXPOSE instruction indicates the ports on which a container will listen for connections. Consequently, you should use the common, traditional port for your application. For example, an image containing the Apache web server would use EXPOSE 80, while an image containing MongoDB would use EXPOSE 27017 and so on.

For external access, your users can execute docker run with a flag indicating how to map the specified port to the port of their choice. For container linking, Docker provides environment variables for the path from the recipient container back to the source (ie, MYSQL_PORT_3306_TCP).

ENV

Dockerfile reference for the ENV instruction

In order 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 will ensure that CMD [“nginx”]just works.

The ENV instruction is also useful for providing required environment variables specific to services you wish to containerize, such as Postgres’s 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 PG_MAJOR 9.3
ENV PG_VERSION 9.3.4
RUN curl -SL http://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.

ADD or COPY

Dockerfile reference for the ADD instruction
Dockerfile reference for the COPY instruction

Although ADD and COPY are functionally similar, generally speaking, COPY is preferred. That’s because it’s more transparent than ADDCOPY only supports the basic copying of local files into the container, while ADD has some features (like local-only tar extraction and remote URL support) that are not immediately obvious. Consequently, the best use for ADD is local tar file auto-extraction into the image, as in ADD rootfs.tar.xz /.

If you have multiple Dockerfile steps that use different files from your context, COPY them individually, rather than all at once. This will ensure that each step’s build cache is only invalidated (forcing the step to be re-run) if the specifically required files change.

For example:

COPY requirements.txt /tmp/
RUN pip install --requirement /tmp/requirements.txt
COPY . /tmp/

Results in fewer cache invalidations for the RUN step, than if you put the COPY . /tmp/ before it.

Because image size matters, using ADD to fetch packages from remote URLs is strongly discouraged; you should use curl or wget instead. That way you can delete the files you no longer need after they’ve been extracted and you won’t have to add another layer in your image. For example, you should avoid doing things like:

ADD http://example.com/big.tar.xz /usr/src/things/
RUN tar -xJf /usr/src/things/big.tar.xz -C /usr/src/things
RUN make -C /usr/src/things all

And instead, do something like:

RUN mkdir -p /usr/src/things \
    && curl -SL http://example.com/big.tar.xz \
    | tar -xJC /usr/src/things \
    && make -C /usr/src/things all

For other items (files, directories) that do not require ADD’s tar auto-extraction capability, you should always use COPY.

ENTRYPOINT

Dockerfile reference for the ENTRYPOINT instruction

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).

Let’s start with an example of an image for the command line tool 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.

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

#!/bin/bashset -eif [ "$1" = 'postgres' ]; then    chown -R postgres "$PGDATA"

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

Note: 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. See the ENTRYPOINT help for more details.

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

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

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

It can simply start Postgres:

$ docker run postgres

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

$ docker run postgres postgres --help

Lastly, it could also be used to start a totally different tool, such as Bash:

$ docker run --rm -it postgres bash

VOLUME

Dockerfile reference for the VOLUME instruction

The VOLUME instruction should be used to expose any database storage area, configuration storage, or files/folders created by your docker container. You are strongly encouraged to use VOLUME for any mutable and/or user-serviceable parts of your image.

USER

Dockerfile reference for the USER instruction

If a service can run without privileges, use USER to change to a non-root user. Start by creating the user and group in the Dockerfile with something like RUN groupadd -r postgres && useradd --no-log-init -r -g postgres postgres.

Note: Users and groups in an image get a non-deterministic UID/GID in that the “next” UID/GID gets assigned regardless of image rebuilds. So, if it’s critical, you should assign an explicit UID/GID.

Note: Due to an unresolved bug in the Go archive/tar package’s handling of sparse files, attempting to create a user with a sufficiently large UID inside a Docker container can lead to disk exhaustion as /var/log/faillog in the container layer is filled with NUL (\0) characters. Passing the --no-log-init flag to useradd works around this issue. The Debian/Ubuntu adduser wrapper does not support the --no-log-init flag and should be avoided.

You should avoid installing or using sudo since it has unpredictable TTY and signal-forwarding behavior that can cause more problems than it solves. If you absolutely need functionality similar to sudo (e.g., initializing the daemon as root but running it as non-root), you may be able to use “gosu”.

Lastly, to reduce layers and complexity, avoid switching USER back and forth frequently.

WORKDIR

Dockerfile reference for the WORKDIR instruction

For clarity and reliability, you should always use absolute paths for your WORKDIR. Also, you should use WORKDIR instead of proliferating instructions like RUN cd … && do-something, which are hard to read, troubleshoot, and maintain.

ONBUILD

Dockerfile reference for the ONBUILD instruction

An ONBUILD command executes after the current Dockerfile build completes. ONBUILD executes in any child image derived FROM the current image. Think of the ONBUILD command as an instruction the parent Dockerfile gives to the child Dockerfile.

A Docker build executes ONBUILD commands before any command in a child Dockerfile.

ONBUILD is useful for images that are going to be built FROM a given image. For example, you would use ONBUILD for a language stack image that builds arbitrary user software written in that language within the Dockerfile, as you can see in Ruby’s ONBUILD variants.

Images built from ONBUILD should get a separate tag, for example: ruby:1.9-onbuild or ruby:2.0-onbuild.

Be careful when putting ADD or COPY in ONBUILD. The “onbuild” image will fail catastrophically if the new build’s context is missing the resource being added. Adding a separate tag, as recommended above, will help mitigate this by allowing the Dockerfile author to make a choice.

Examples for Official Repositories

These Official Repositories have exemplary Dockerfiles:

Additional resources:

转载自:https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/#examples-for-official-repositories

anzhihe安志合个人博客,版权所有丨 如未注明,均为原创 丨转载请注明转自:https://chegva.com/2609.html | ☆★★每天进步一点点,加油!★★☆

您可能还感兴趣的文章!

发表评论

电子邮件地址不会被公开。 必填项已用*标注