github.com/chenchun/docker@v1.3.2-0.20150629222414-20467faf132b/docs/articles/dockerfile_best-practices.md (about) 1 <!--[metadata]> 2 +++ 3 title = "Best practices for writing Dockerfiles" 4 description = "Hints, tips and guidelines for writing clean, reliable Dockerfiles" 5 keywords = ["Examples, Usage, base image, docker, documentation, dockerfile, best practices, hub, official repo"] 6 [menu.main] 7 parent = "smn_images" 8 +++ 9 <![end-metadata]--> 10 11 # Best practices for writing Dockerfiles 12 13 ## Overview 14 15 Docker can build images automatically by reading the instructions from a 16 `Dockerfile`, a text file that contains all the commands, in order, needed to 17 build a given image. `Dockerfile`s adhere to a specific format and use a 18 specific set of instructions. You can learn the basics on the 19 [Dockerfile Reference](https://docs.docker.com/reference/builder/) page. If 20 you’re new to writing `Dockerfile`s, you should start there. 21 22 This document covers the best practices and methods recommended by Docker, 23 Inc. and the Docker community for creating easy-to-use, effective 24 `Dockerfile`s. We strongly suggest you follow these recommendations (in fact, 25 if you’re creating an Official Image, you *must* adhere to these practices). 26 27 You can see many of these practices and recommendations in action in the [buildpack-deps `Dockerfile`](https://github.com/docker-library/buildpack-deps/blob/master/jessie/Dockerfile). 28 29 > Note: for more detailed explanations of any of the Dockerfile commands 30 >mentioned here, visit the [Dockerfile Reference](https://docs.docker.com/reference/builder/) page. 31 32 ## General guidelines and recommendations 33 34 ### Containers should be ephemeral 35 36 The container produced by the image your `Dockerfile` defines should be as 37 ephemeral as possible. By “ephemeral,” we mean that it can be stopped and 38 destroyed and a new one built and put in place with an absolute minimum of 39 set-up and configuration. 40 41 ### Use a .dockerignore file 42 43 In most cases, it's best to put each Dockerfile in an empty directory. Then, 44 add to that directory only the files needed for building the Dockerfile. To 45 increase the build's performance, you can exclude files and directories by 46 adding a `.dockerignore` file to that directory as well. This file supports 47 exclusion patterns similar to `.gitignore` files. For information on creating one, 48 see the [.dockerignore file](../../reference/builder/#dockerignore-file). 49 50 ### Avoid installing unnecessary packages 51 52 In order to reduce complexity, dependencies, file sizes, and build times, you 53 should avoid installing extra or unnecessary packages just because they 54 might be “nice to have.” For example, you don’t need to include a text editor 55 in a database image. 56 57 ### Run only one process per container 58 59 In almost all cases, you should only run a single process in a single 60 container. Decoupling applications into multiple containers makes it much 61 easier to scale horizontally and reuse containers. If that service depends on 62 another service, make use of [container linking](https://docs.docker.com/userguide/dockerlinks/). 63 64 ### Minimize the number of layers 65 66 You need to find the balance between readability (and thus long-term 67 maintainability) of the `Dockerfile` and minimizing the number of layers it 68 uses. Be strategic and cautious about the number of layers you use. 69 70 ### Sort multi-line arguments 71 72 Whenever possible, ease later changes by sorting multi-line arguments 73 alphanumerically. This will help you avoid duplication of packages and make the 74 list much easier to update. This also makes PRs a lot easier to read and 75 review. Adding a space before a backslash (`\`) helps as well. 76 77 Here’s an example from the [`buildpack-deps` image](https://github.com/docker-library/buildpack-deps): 78 79 RUN apt-get update && apt-get install -y \ 80 bzr \ 81 cvs \ 82 git \ 83 mercurial \ 84 subversion 85 86 ### Build cache 87 88 During the process of building an image Docker will step through the 89 instructions in your `Dockerfile` executing each in the order specified. 90 As each instruction is examined Docker will look for an existing image in its 91 cache that it can reuse, rather than creating a new (duplicate) image. 92 If you do not want to use the cache at all you can use the ` --no-cache=true` 93 option on the `docker build` command. 94 95 However, if you do let Docker use its cache then it is very important to 96 understand when it will, and will not, find a matching image. The basic rules 97 that Docker will follow are outlined below: 98 99 * Starting with a base image that is already in the cache, the next 100 instruction is compared against all child images derived from that base 101 image to see if one of them was built using the exact same instruction. If 102 not, the cache is invalidated. 103 104 * In most cases simply comparing the instruction in the `Dockerfile` with one 105 of the child images is sufficient. However, certain instructions require 106 a little more examination and explanation. 107 108 * In the case of the `ADD` and `COPY` instructions, the contents of the file(s) 109 being put into the image are examined. Specifically, a checksum is done 110 of the file(s) and then that checksum is used during the cache lookup. 111 If anything has changed in the file(s), including its metadata, 112 then the cache is invalidated. The last-modified and last-accessed times of the 113 file(s) are not considered in these checksums. 114 115 * Aside from the `ADD` and `COPY` commands cache checking will not look at the 116 files in the container to determine a cache match. For example, when processing 117 a `RUN apt-get -y update` command the files updated in the container 118 will not be examined to determine if a cache hit exists. In that case just 119 the command string itself will be used to find a match. 120 121 Once the cache is invalidated, all subsequent `Dockerfile` commands will 122 generate new images and the cache will not be used. 123 124 ## The Dockerfile instructions 125 126 Below you'll find recommendations for the best way to write the 127 various instructions available for use in a `Dockerfile`. 128 129 ### [`FROM`](https://docs.docker.com/reference/builder/#from) 130 131 Whenever possible, use current Official Repositories as the basis for your 132 image. We recommend the [Debian image](https://registry.hub.docker.com/_/debian/) 133 since it’s very tightly controlled and kept extremely minimal (currently under 134 100 mb), while still being a full distribution. 135 136 ### [`RUN`](https://docs.docker.com/reference/builder/#run) 137 138 As always, to make your `Dockerfile` more readable, understandable, and 139 maintainable, put long or complex `RUN` statements on multiple lines separated 140 with backslashes. 141 142 Probably the most common use-case for `RUN` is an application of `apt-get`. 143 When using `apt-get`, here are a few things to keep in mind: 144 145 * Don’t do `RUN apt-get update` on a single line. This will cause 146 caching issues if the referenced archive gets updated, which will make your 147 subsequent `apt-get install` fail without comment. 148 149 * Avoid `RUN apt-get upgrade` or `dist-upgrade`, since many of the “essential” 150 packages from the base images will fail to upgrade inside an unprivileged 151 container. If a base package is out of date, you should contact its 152 maintainers. If you know there’s a particular package, `foo`, that needs to be 153 updated, use `apt-get install -y foo` and it will update automatically. 154 155 * Do write instructions like: 156 157 RUN apt-get update && apt-get install -y package-bar package-foo package-baz 158 159 Writing the instruction this way not only makes it easier to read 160 and maintain, but also, by including `apt-get update`, ensures that the cache 161 will naturally be busted and the latest versions will be installed with no 162 further coding or manual intervention required. 163 164 * Further natural cache-busting can be realized by version-pinning packages 165 (e.g., `package-foo=1.3.*`). This will force retrieval of that version 166 regardless of what’s in the cache. 167 Writing your `apt-get` code this way will greatly ease maintenance and reduce 168 failures due to unanticipated changes in required packages. 169 170 #### Example 171 172 Below is a well-formed `RUN` instruction that demonstrates the above 173 recommendations. Note that the last package, `s3cmd`, specifies a version 174 `1.1.0*`. If the image previously used an older version, specifying the new one 175 will cause a cache bust of `apt-get update` and ensure the installation of 176 the new version (which in this case had a new, required feature). 177 178 RUN apt-get update && apt-get install -y \ 179 aufs-tools \ 180 automake \ 181 btrfs-tools \ 182 build-essential \ 183 curl \ 184 dpkg-sig \ 185 git \ 186 iptables \ 187 libapparmor-dev \ 188 libcap-dev \ 189 libsqlite3-dev \ 190 lxc=1.0* \ 191 mercurial \ 192 parallel \ 193 reprepro \ 194 ruby1.9.1 \ 195 ruby1.9.1-dev \ 196 s3cmd=1.1.0* 197 198 Writing the instruction this way also helps you avoid potential duplication of 199 a given package because it is much easier to read than an instruction like: 200 201 RUN apt-get install -y package-foo && apt-get install -y package-bar 202 203 ### [`CMD`](https://docs.docker.com/reference/builder/#cmd) 204 205 The `CMD` instruction should be used to run the software contained by your 206 image, along with any arguments. `CMD` should almost always be used in the 207 form of `CMD [“executable”, “param1”, “param2”…]`. Thus, if the image is for a 208 service (Apache, Rails, etc.), you would run something like 209 `CMD ["apache2","-DFOREGROUND"]`. Indeed, this form of the instruction is 210 recommended for any service-based image. 211 212 In most other cases, `CMD` should be given an interactive shell (bash, python, 213 perl, etc), for example, `CMD ["perl", "-de0"]`, `CMD ["python"]`, or 214 `CMD [“php”, “-a”]`. Using this form means that when you execute something like 215 `docker run -it python`, you’ll get dropped into a usable shell, ready to go. 216 `CMD` should rarely be used in the manner of `CMD [“param”, “param”]` in 217 conjunction with [`ENTRYPOINT`](https://docs.docker.com/reference/builder/#entrypoint), unless 218 you and your expected users are already quite familiar with how `ENTRYPOINT` 219 works. 220 221 ### [`EXPOSE`](https://docs.docker.com/reference/builder/#expose) 222 223 The `EXPOSE` instruction indicates the ports on which a container will listen 224 for connections. Consequently, you should use the common, traditional port for 225 your application. For example, an image containing the Apache web server would 226 use `EXPOSE 80`, while an image containing MongoDB would use `EXPOSE 27017` and 227 so on. 228 229 For external access, your users can execute `docker run` with a flag indicating 230 how to map the specified port to the port of their choice. 231 For container linking, Docker provides environment variables for the path from 232 the recipient container back to the source (ie, `MYSQL_PORT_3306_TCP`). 233 234 ### [`ENV`](https://docs.docker.com/reference/builder/#env) 235 236 In order to make new software easier to run, you can use `ENV` to update the 237 `PATH` environment variable for the software your container installs. For 238 example, `ENV PATH /usr/local/nginx/bin:$PATH` will ensure that `CMD [“nginx”]` 239 just works. 240 241 The `ENV` instruction is also useful for providing required environment 242 variables specific to services you wish to containerize, such as Postgres’s 243 `PGDATA`. 244 245 Lastly, `ENV` can also be used to set commonly used version numbers so that 246 version bumps are easier to maintain, as seen in the following example: 247 248 ENV PG_MAJOR 9.3 249 ENV PG_VERSION 9.3.4 250 RUN curl -SL http://example.com/postgres-$PG_VERSION.tar.xz | tar -xJC /usr/src/postgress && … 251 ENV PATH /usr/local/postgres-$PG_MAJOR/bin:$PATH 252 253 Similar to having constant variables in a program (as opposed to hard-coding 254 values), this approach lets you change a single `ENV` instruction to 255 auto-magically bump the version of the software in your container. 256 257 ### [`ADD`](https://docs.docker.com/reference/builder/#add) or [`COPY`](https://docs.docker.com/reference/builder/#copy) 258 259 Although `ADD` and `COPY` are functionally similar, generally speaking, `COPY` 260 is preferred. That’s because it’s more transparent than `ADD`. `COPY` only 261 supports the basic copying of local files into the container, while `ADD` has 262 some features (like local-only tar extraction and remote URL support) that are 263 not immediately obvious. Consequently, the best use for `ADD` is local tar file 264 auto-extraction into the image, as in `ADD rootfs.tar.xz /`. 265 266 If you have multiple `Dockerfile` steps that use different files from your 267 context, `COPY` them individually, rather than all at once. This will ensure that 268 each step's build cache is only invalidated (forcing the step to be re-run) if the 269 specifically required files change. 270 271 For example: 272 273 COPY requirements.txt /tmp/ 274 RUN pip install /tmp/requirements.txt 275 COPY . /tmp/ 276 277 Results in fewer cache invalidations for the `RUN` step, than if you put the 278 `COPY . /tmp/` before it. 279 280 Because image size matters, using `ADD` to fetch packages from remote URLs is 281 strongly discouraged; you should use `curl` or `wget` instead. That way you can 282 delete the files you no longer need after they've been extracted and you won't 283 have to add another layer in your image. For example, you should avoid doing 284 things like: 285 286 ADD http://example.com/big.tar.xz /usr/src/things/ 287 RUN tar -xJf /usr/src/things/big.tar.xz -C /usr/src/things 288 RUN make -C /usr/src/things all 289 290 And instead, do something like: 291 292 RUN mkdir -p /usr/src/things \ 293 && curl -SL http://example.com/big.tar.xz \ 294 | tar -xJC /usr/src/things \ 295 && make -C /usr/src/things all 296 297 For other items (files, directories) that do not require `ADD`’s tar 298 auto-extraction capability, you should always use `COPY`. 299 300 ### [`ENTRYPOINT`](https://docs.docker.com/reference/builder/#entrypoint) 301 302 The best use for `ENTRYPOINT` is to set the image's main command, allowing that 303 image to be run as though it was that command (and then use `CMD` as the 304 default flags). 305 306 Let's start with an example of an image for the command line tool `s3cmd`: 307 308 ENTRYPOINT ["s3cmd"] 309 CMD ["--help"] 310 311 Now the image can be run like this to show the command's help: 312 313 $ docker run s3cmd 314 315 Or using the right parameters to execute a command: 316 317 $ docker run s3cmd ls s3://mybucket 318 319 This is useful because the image name can double as a reference to the binary as 320 shown in the command above. 321 322 The `ENTRYPOINT` instruction can also be used in combination with a helper 323 script, allowing it to function in a similar way to the command above, even 324 when starting the tool may require more than one step. 325 326 For example, the [Postgres Official Image](https://registry.hub.docker.com/_/postgres/) 327 uses the following script as its `ENTRYPOINT`: 328 329 ```bash 330 #!/bin/bash 331 set -e 332 333 if [ "$1" = 'postgres' ]; then 334 chown -R postgres "$PGDATA" 335 336 if [ -z "$(ls -A "$PGDATA")" ]; then 337 gosu postgres initdb 338 fi 339 340 exec gosu postgres "$@" 341 fi 342 343 exec "$@" 344 ``` 345 346 > **Note**: 347 > This script uses [the `exec` Bash command](http://wiki.bash-hackers.org/commands/builtin/exec) 348 > so that the final running application becomes the container's PID 1. This allows 349 > the application to receive any Unix signals sent to the container. 350 > See the [`ENTRYPOINT`](https://docs.docker.com/reference/builder/#ENTRYPOINT) 351 > help for more details. 352 353 354 The helper script is copied into the container and run via `ENTRYPOINT` on 355 container start: 356 357 COPY ./docker-entrypoint.sh / 358 ENTRYPOINT ["/docker-entrypoint.sh"] 359 360 This script allows the user to interact with Postgres in several ways. 361 362 It can simply start Postgres: 363 364 $ docker run postgres 365 366 Or, it can be used to run Postgres and pass parameters to the server: 367 368 $ docker run postgres postgres --help 369 370 Lastly, it could also be used to start a totally different tool, such Bash: 371 372 $ docker run --rm -it postgres bash 373 374 ### [`VOLUME`](https://docs.docker.com/reference/builder/#volume) 375 376 The `VOLUME` instruction should be used to expose any database storage area, 377 configuration storage, or files/folders created by your docker container. You 378 are strongly encouraged to use `VOLUME` for any mutable and/or user-serviceable 379 parts of your image. 380 381 ### [`USER`](https://docs.docker.com/reference/builder/#user) 382 383 If a service can run without privileges, use `USER` to change to a non-root 384 user. Start by creating the user and group in the `Dockerfile` with something 385 like `RUN groupadd -r postgres && useradd -r -g postgres postgres`. 386 387 > **Note:** Users and groups in an image get a non-deterministic 388 > UID/GID in that the “next” UID/GID gets assigned regardless of image 389 > rebuilds. So, if it’s critical, you should assign an explicit UID/GID. 390 391 You should avoid installing or using `sudo` since it has unpredictable TTY and 392 signal-forwarding behavior that can cause more problems than it solves. If 393 you absolutely need functionality similar to `sudo` (e.g., initializing the 394 daemon as root but running it as non-root), you may be able to use 395 [“gosu”](https://github.com/tianon/gosu). 396 397 Lastly, to reduce layers and complexity, avoid switching `USER` back 398 and forth frequently. 399 400 ### [`WORKDIR`](https://docs.docker.com/reference/builder/#workdir) 401 402 For clarity and reliability, you should always use absolute paths for your 403 `WORKDIR`. Also, you should use `WORKDIR` instead of proliferating 404 instructions like `RUN cd … && do-something`, which are hard to read, 405 troubleshoot, and maintain. 406 407 ### [`ONBUILD`](https://docs.docker.com/reference/builder/#onbuild) 408 409 An `ONBUILD` command executes after the current `Dockerfile` build completes. 410 `ONBUILD` executes in any child image derived `FROM` the current image. Think 411 of the `ONBUILD` command as an instruction the parent `Dockerfile` gives 412 to the child `Dockerfile`. 413 414 A Docker build executes `ONBUILD` commands before any command in a child 415 `Dockerfile`. 416 417 `ONBUILD` is useful for images that are going to be built `FROM` a given 418 image. For example, you would use `ONBUILD` for a language stack image that 419 builds arbitrary user software written in that language within the 420 `Dockerfile`, as you can see in [Ruby’s `ONBUILD` variants](https://github.com/docker-library/ruby/blob/master/2.1/onbuild/Dockerfile). 421 422 Images built from `ONBUILD` should get a separate tag, for example: 423 `ruby:1.9-onbuild` or `ruby:2.0-onbuild`. 424 425 Be careful when putting `ADD` or `COPY` in `ONBUILD`. The “onbuild” image will 426 fail catastrophically if the new build's context is missing the resource being 427 added. Adding a separate tag, as recommended above, will help mitigate this by 428 allowing the `Dockerfile` author to make a choice. 429 430 ## Examples for Official Repositories 431 432 These Official Repositories have exemplary `Dockerfile`s: 433 434 * [Go](https://registry.hub.docker.com/_/golang/) 435 * [Perl](https://registry.hub.docker.com/_/perl/) 436 * [Hy](https://registry.hub.docker.com/_/hylang/) 437 * [Rails](https://registry.hub.docker.com/_/rails) 438 439 ## Additional resources: 440 441 * [Dockerfile Reference](https://docs.docker.com/reference/builder/#onbuild) 442 * [More about Base Images](https://docs.docker.com/articles/baseimages/) 443 * [More about Automated Builds](https://docs.docker.com/docker-hub/builds/) 444 * [Guidelines for Creating Official 445 Repositories](https://docs.docker.com/docker-hub/official_repos/)