github.com/panekj/cli@v0.0.0-20230304125325-467dd2f3797e/docs/reference/commandline/build.md (about)

     1  # build
     2  
     3  <!---MARKER_GEN_START-->
     4  Build an image from a Dockerfile
     5  
     6  ### Aliases
     7  
     8  `docker image build`, `docker build`, `docker buildx build`, `docker builder build`
     9  
    10  ### Options
    11  
    12  | Name                                | Type          | Default   | Description                                                       |
    13  |:------------------------------------|:--------------|:----------|:------------------------------------------------------------------|
    14  | [`--add-host`](#add-host)           | `list`        |           | Add a custom host-to-IP mapping (`host:ip`)                       |
    15  | [`--build-arg`](#build-arg)         | `list`        |           | Set build-time variables                                          |
    16  | [`--cache-from`](#cache-from)       | `stringSlice` |           | Images to consider as cache sources                               |
    17  | [`--cgroup-parent`](#cgroup-parent) | `string`      |           | Optional parent cgroup for the container                          |
    18  | `--compress`                        |               |           | Compress the build context using gzip                             |
    19  | `--cpu-period`                      | `int64`       | `0`       | Limit the CPU CFS (Completely Fair Scheduler) period              |
    20  | `--cpu-quota`                       | `int64`       | `0`       | Limit the CPU CFS (Completely Fair Scheduler) quota               |
    21  | `-c`, `--cpu-shares`                | `int64`       | `0`       | CPU shares (relative weight)                                      |
    22  | `--cpuset-cpus`                     | `string`      |           | CPUs in which to allow execution (0-3, 0,1)                       |
    23  | `--cpuset-mems`                     | `string`      |           | MEMs in which to allow execution (0-3, 0,1)                       |
    24  | `--disable-content-trust`           |               |           | Skip image verification                                           |
    25  | [`-f`](#file), [`--file`](#file)    | `string`      |           | Name of the Dockerfile (Default is `PATH/Dockerfile`)             |
    26  | `--force-rm`                        |               |           | Always remove intermediate containers                             |
    27  | `--iidfile`                         | `string`      |           | Write the image ID to the file                                    |
    28  | [`--isolation`](#isolation)         | `string`      |           | Container isolation technology                                    |
    29  | `--label`                           | `list`        |           | Set metadata for an image                                         |
    30  | `-m`, `--memory`                    | `bytes`       | `0`       | Memory limit                                                      |
    31  | `--memory-swap`                     | `bytes`       | `0`       | Swap limit equal to memory plus swap: -1 to enable unlimited swap |
    32  | `--network`                         | `string`      | `default` | Set the networking mode for the RUN instructions during build     |
    33  | `--no-cache`                        |               |           | Do not use cache when building the image                          |
    34  | `--platform`                        | `string`      |           | Set platform if server is multi-platform capable                  |
    35  | `--pull`                            |               |           | Always attempt to pull a newer version of the image               |
    36  | `-q`, `--quiet`                     |               |           | Suppress the build output and print image ID on success           |
    37  | `--rm`                              |               |           | Remove intermediate containers after a successful build           |
    38  | [`--security-opt`](#security-opt)   | `stringSlice` |           | Security options                                                  |
    39  | `--shm-size`                        | `bytes`       | `0`       | Size of `/dev/shm`                                                |
    40  | [`--squash`](#squash)               |               |           | Squash newly built layers into a single new layer                 |
    41  | [`-t`](#tag), [`--tag`](#tag)       | `list`        |           | Name and optionally a tag in the `name:tag` format                |
    42  | [`--target`](#target)               | `string`      |           | Set the target build stage to build.                              |
    43  | [`--ulimit`](#ulimit)               | `ulimit`      |           | Ulimit options                                                    |
    44  
    45  
    46  <!---MARKER_GEN_END-->
    47  
    48  ## Description
    49  
    50  The `docker build` command builds Docker images from a Dockerfile and a
    51  "context". A build's context is the set of files located in the specified
    52  `PATH` or `URL`. The build process can refer to any of the files in the
    53  context. For example, your build can use a [*COPY*](https://docs.docker.com/engine/reference/builder/#copy)
    54  instruction to reference a file in the context.
    55  
    56  The `URL` parameter can refer to three kinds of resources: Git repositories,
    57  pre-packaged tarball contexts and plain text files.
    58  
    59  ### Git repositories
    60  
    61  When the `URL` parameter points to the location of a Git repository, the
    62  repository acts as the build context. The system recursively fetches the
    63  repository and its submodules. The commit history is not preserved. A
    64  repository is first pulled into a temporary directory on your local host. After
    65  that succeeds, the directory is sent to the Docker daemon as the context.
    66  Local copy gives you the ability to access private repositories using local
    67  user credentials, VPN's, and so forth.
    68  
    69  > **Note**
    70  >
    71  > If the `URL` parameter contains a fragment the system will recursively clone
    72  > the repository and its submodules using a `git clone --recursive` command.
    73  
    74  Git URLs accept context configuration in their fragment section, separated by a
    75  colon (`:`).  The first part represents the reference that Git will check out,
    76  and can be either a branch, a tag, or a remote reference. The second part
    77  represents a subdirectory inside the repository that will be used as a build
    78  context.
    79  
    80  For example, run this command to use a directory called `docker` in the branch
    81  `container`:
    82  
    83  ```console
    84  $ docker build https://github.com/docker/rootfs.git#container:docker
    85  ```
    86  
    87  The following table represents all the valid suffixes with their build
    88  contexts:
    89  
    90  | Build Syntax Suffix            | Commit Used           | Build Context Used |
    91  |--------------------------------|-----------------------|--------------------|
    92  | `myrepo.git`                   | `refs/heads/master`   | `/`                |
    93  | `myrepo.git#mytag`             | `refs/tags/mytag`     | `/`                |
    94  | `myrepo.git#mybranch`          | `refs/heads/mybranch` | `/`                |
    95  | `myrepo.git#pull/42/head`      | `refs/pull/42/head`   | `/`                |
    96  | `myrepo.git#:myfolder`         | `refs/heads/master`   | `/myfolder`        |
    97  | `myrepo.git#master:myfolder`   | `refs/heads/master`   | `/myfolder`        |
    98  | `myrepo.git#mytag:myfolder`    | `refs/tags/mytag`     | `/myfolder`        |
    99  | `myrepo.git#mybranch:myfolder` | `refs/heads/mybranch` | `/myfolder`        |
   100  
   101  ### Tarball contexts
   102  
   103  If you pass an URL to a remote tarball, the URL itself is sent to the daemon:
   104  
   105  ```console
   106  $ docker build http://server/context.tar.gz
   107  ```
   108  
   109  The download operation will be performed on the host the Docker daemon is
   110  running on, which is not necessarily the same host from which the build command
   111  is being issued. The Docker daemon will fetch `context.tar.gz` and use it as the
   112  build context. Tarball contexts must be tar archives conforming to the standard
   113  `tar` UNIX format and can be compressed with any one of the 'xz', 'bzip2',
   114  'gzip' or 'identity' (no compression) formats.
   115  
   116  ### Text files
   117  
   118  Instead of specifying a context, you can pass a single `Dockerfile` in the
   119  `URL` or pipe the file in via `STDIN`. To pipe a `Dockerfile` from `STDIN`:
   120  
   121  ```console
   122  $ docker build - < Dockerfile
   123  ```
   124  
   125  With Powershell on Windows, you can run:
   126  
   127  ```powershell
   128  Get-Content Dockerfile | docker build -
   129  ```
   130  
   131  If you use `STDIN` or specify a `URL` pointing to a plain text file, the system
   132  places the contents into a file called `Dockerfile`, and any `-f`, `--file`
   133  option is ignored. In this scenario, there is no context.
   134  
   135  By default the `docker build` command will look for a `Dockerfile` at the root
   136  of the build context. The `-f`, `--file`, option lets you specify the path to
   137  an alternative file to use instead. This is useful in cases where the same set
   138  of files are used for multiple builds. The path must be to a file within the
   139  build context. If a relative path is specified then it is interpreted as
   140  relative to the root of the context.
   141  
   142  In most cases, it's best to put each Dockerfile in an empty directory. Then,
   143  add to that directory only the files needed for building the Dockerfile. To
   144  increase the build's performance, you can exclude files and directories by
   145  adding a `.dockerignore` file to that directory as well. For information on
   146  creating one, see the [.dockerignore file](https://docs.docker.com/engine/reference/builder/#dockerignore-file).
   147  
   148  If the Docker client loses connection to the daemon, the build is canceled.
   149  This happens if you interrupt the Docker client with `CTRL-c` or if the Docker
   150  client is killed for any reason. If the build initiated a pull which is still
   151  running at the time the build is cancelled, the pull is cancelled as well.
   152  
   153  ## Return code
   154  
   155  On a successful build, a return code of success `0` will be returned.  When the
   156  build fails, a non-zero failure code will be returned.
   157  
   158  There should be informational output of the reason for failure output to
   159  `STDERR`:
   160  
   161  ```console
   162  $ docker build -t fail .
   163  
   164  Sending build context to Docker daemon 2.048 kB
   165  Sending build context to Docker daemon
   166  Step 1/3 : FROM busybox
   167   ---> 4986bf8c1536
   168  Step 2/3 : RUN exit 13
   169   ---> Running in e26670ec7a0a
   170  INFO[0000] The command [/bin/sh -c exit 13] returned a non-zero code: 13
   171  $ echo $?
   172  1
   173  ```
   174  
   175  See also:
   176  
   177  [*Dockerfile Reference*](https://docs.docker.com/engine/reference/builder/).
   178  
   179  ## Examples
   180  
   181  ### Build with PATH
   182  
   183  ```console
   184  $ docker build .
   185  
   186  Uploading context 10240 bytes
   187  Step 1/3 : FROM busybox
   188  Pulling repository busybox
   189   ---> e9aa60c60128MB/2.284 MB (100%) endpoint: https://cdn-registry-1.docker.io/v1/
   190  Step 2/3 : RUN ls -lh /
   191   ---> Running in 9c9e81692ae9
   192  total 24
   193  drwxr-xr-x    2 root     root        4.0K Mar 12  2013 bin
   194  drwxr-xr-x    5 root     root        4.0K Oct 19 00:19 dev
   195  drwxr-xr-x    2 root     root        4.0K Oct 19 00:19 etc
   196  drwxr-xr-x    2 root     root        4.0K Nov 15 23:34 lib
   197  lrwxrwxrwx    1 root     root           3 Mar 12  2013 lib64 -> lib
   198  dr-xr-xr-x  116 root     root           0 Nov 15 23:34 proc
   199  lrwxrwxrwx    1 root     root           3 Mar 12  2013 sbin -> bin
   200  dr-xr-xr-x   13 root     root           0 Nov 15 23:34 sys
   201  drwxr-xr-x    2 root     root        4.0K Mar 12  2013 tmp
   202  drwxr-xr-x    2 root     root        4.0K Nov 15 23:34 usr
   203   ---> b35f4035db3f
   204  Step 3/3 : CMD echo Hello world
   205   ---> Running in 02071fceb21b
   206   ---> f52f38b7823e
   207  Successfully built f52f38b7823e
   208  Removing intermediate container 9c9e81692ae9
   209  Removing intermediate container 02071fceb21b
   210  ```
   211  
   212  This example specifies that the `PATH` is `.`, and so all the files in the
   213  local directory get `tar`d and sent to the Docker daemon. The `PATH` specifies
   214  where to find the files for the "context" of the build on the Docker daemon.
   215  Remember that the daemon could be running on a remote machine and that no
   216  parsing of the Dockerfile happens at the client side (where you're running
   217  `docker build`). That means that *all* the files at `PATH` get sent, not just
   218  the ones listed to [*ADD*](https://docs.docker.com/engine/reference/builder/#add)
   219  in the Dockerfile.
   220  
   221  The transfer of context from the local machine to the Docker daemon is what the
   222  `docker` client means when you see the "Sending build context" message.
   223  
   224  If you wish to keep the intermediate containers after the build is complete,
   225  you must use `--rm=false`. This does not affect the build cache.
   226  
   227  ### Build with URL
   228  
   229  ```console
   230  $ docker build github.com/creack/docker-firefox
   231  ```
   232  
   233  This will clone the GitHub repository and use the cloned repository as context.
   234  The Dockerfile at the root of the repository is used as Dockerfile. You can
   235  specify an arbitrary Git repository by using the `git://` or `git@` scheme.
   236  
   237  ```console
   238  $ docker build -f ctx/Dockerfile http://server/ctx.tar.gz
   239  
   240  Downloading context: http://server/ctx.tar.gz [===================>]    240 B/240 B
   241  Step 1/3 : FROM busybox
   242   ---> 8c2e06607696
   243  Step 2/3 : ADD ctx/container.cfg /
   244   ---> e7829950cee3
   245  Removing intermediate container b35224abf821
   246  Step 3/3 : CMD /bin/ls
   247   ---> Running in fbc63d321d73
   248   ---> 3286931702ad
   249  Removing intermediate container fbc63d321d73
   250  Successfully built 377c409b35e4
   251  ```
   252  
   253  This sends the URL `http://server/ctx.tar.gz` to the Docker daemon, which
   254  downloads and extracts the referenced tarball. The `-f ctx/Dockerfile`
   255  parameter specifies a path inside `ctx.tar.gz` to the `Dockerfile` that is used
   256  to build the image. Any `ADD` commands in that `Dockerfile` that refers to local
   257  paths must be relative to the root of the contents inside `ctx.tar.gz`. In the
   258  example above, the tarball contains a directory `ctx/`, so the `ADD
   259  ctx/container.cfg /` operation works as expected.
   260  
   261  ### Build with -
   262  
   263  ```console
   264  $ docker build - < Dockerfile
   265  ```
   266  
   267  This will read a Dockerfile from `STDIN` without context. Due to the lack of a
   268  context, no contents of any local directory will be sent to the Docker daemon.
   269  Since there is no context, a Dockerfile `ADD` only works if it refers to a
   270  remote URL.
   271  
   272  ```console
   273  $ docker build - < context.tar.gz
   274  ```
   275  
   276  This will build an image for a compressed context read from `STDIN`.  Supported
   277  formats are: bzip2, gzip and xz.
   278  
   279  ### Use a .dockerignore file
   280  
   281  ```console
   282  $ docker build .
   283  
   284  Uploading context 18.829 MB
   285  Uploading context
   286  Step 1/2 : FROM busybox
   287   ---> 769b9341d937
   288  Step 2/2 : CMD echo Hello world
   289   ---> Using cache
   290   ---> 99cc1ad10469
   291  Successfully built 99cc1ad10469
   292  $ echo ".git" > .dockerignore
   293  $ docker build .
   294  Uploading context  6.76 MB
   295  Uploading context
   296  Step 1/2 : FROM busybox
   297   ---> 769b9341d937
   298  Step 2/2 : CMD echo Hello world
   299   ---> Using cache
   300   ---> 99cc1ad10469
   301  Successfully built 99cc1ad10469
   302  ```
   303  
   304  This example shows the use of the `.dockerignore` file to exclude the `.git`
   305  directory from the context. Its effect can be seen in the changed size of the
   306  uploaded context. The builder reference contains detailed information on
   307  [creating a .dockerignore file](https://docs.docker.com/engine/reference/builder/#dockerignore-file).
   308  
   309  When using the [BuildKit backend](https://docs.docker.com/build/buildkit/),
   310  `docker build` searches for a `.dockerignore` file relative to the Dockerfile
   311  name. For example, running `docker build -f myapp.Dockerfile .` will first look
   312  for an ignore file named `myapp.Dockerfile.dockerignore`. If such a file is not
   313  found, the `.dockerignore` file is used if present. Using a Dockerfile based
   314  `.dockerignore` is useful if a project contains multiple Dockerfiles that expect
   315  to ignore different sets of files.
   316  
   317  
   318  ### <a name="tag"></a> Tag an image (-t, --tag)
   319  
   320  ```console
   321  $ docker build -t vieux/apache:2.0 .
   322  ```
   323  
   324  This will build like the previous example, but it will then tag the resulting
   325  image. The repository name will be `vieux/apache` and the tag will be `2.0`.
   326  [Read more about valid tags](tag.md).
   327  
   328  You can apply multiple tags to an image. For example, you can apply the `latest`
   329  tag to a newly built image and add another tag that references a specific
   330  version.
   331  For example, to tag an image both as `whenry/fedora-jboss:latest` and
   332  `whenry/fedora-jboss:v2.1`, use the following:
   333  
   334  ```console
   335  $ docker build -t whenry/fedora-jboss:latest -t whenry/fedora-jboss:v2.1 .
   336  ```
   337  
   338  ### <a name="file"></a> Specify a Dockerfile (-f, --file)
   339  
   340  ```console
   341  $ docker build -f Dockerfile.debug .
   342  ```
   343  
   344  This will use a file called `Dockerfile.debug` for the build instructions
   345  instead of `Dockerfile`.
   346  
   347  ```console
   348  $ curl example.com/remote/Dockerfile | docker build -f - .
   349  ```
   350  
   351  The above command will use the current directory as the build context and read
   352  a Dockerfile from stdin.
   353  
   354  ```console
   355  $ docker build -f dockerfiles/Dockerfile.debug -t myapp_debug .
   356  $ docker build -f dockerfiles/Dockerfile.prod  -t myapp_prod .
   357  ```
   358  
   359  The above commands will build the current build context (as specified by the
   360  `.`) twice, once using a debug version of a `Dockerfile` and once using a
   361  production version.
   362  
   363  ```console
   364  $ cd /home/me/myapp/some/dir/really/deep
   365  $ docker build -f /home/me/myapp/dockerfiles/debug /home/me/myapp
   366  $ docker build -f ../../../../dockerfiles/debug /home/me/myapp
   367  ```
   368  
   369  These two `docker build` commands do the exact same thing. They both use the
   370  contents of the `debug` file instead of looking for a `Dockerfile` and will use
   371  `/home/me/myapp` as the root of the build context. Note that `debug` is in the
   372  directory structure of the build context, regardless of how you refer to it on
   373  the command line.
   374  
   375  > **Note**
   376  >
   377  > `docker build` returns a `no such file or directory` error if the
   378  > file or directory does not exist in the uploaded context. This may
   379  > happen if there is no context, or if you specify a file that is
   380  > elsewhere on the Host system. The context is limited to the current
   381  > directory (and its children) for security reasons, and to ensure
   382  > repeatable builds on remote Docker hosts. This is also the reason why
   383  > `ADD ../file` does not work.
   384  
   385  ### <a name="cgroup-parent"></a> Use a custom parent cgroup (--cgroup-parent)
   386  
   387  When `docker build` is run with the `--cgroup-parent` option the containers
   388  used in the build will be run with the [corresponding `docker run` flag](../run.md#specify-custom-cgroups).
   389  
   390  ### <a name="ulimit"></a> Set ulimits in container (--ulimit)
   391  
   392  Using the `--ulimit` option with `docker build` will cause each build step's
   393  container to be started using those [`--ulimit` flag values](run.md#ulimit).
   394  
   395  ### <a name="build-arg"></a> Set build-time variables (--build-arg)
   396  
   397  You can use `ENV` instructions in a Dockerfile to define variable
   398  values. These values persist in the built image. However, often
   399  persistence is not what you want. Users want to specify variables differently
   400  depending on which host they build an image on.
   401  
   402  A good example is `http_proxy` or source versions for pulling intermediate
   403  files. The `ARG` instruction lets Dockerfile authors define values that users
   404  can set at build-time using the  `--build-arg` flag:
   405  
   406  ```console
   407  $ docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234 --build-arg FTP_PROXY=http://40.50.60.5:4567 .
   408  ```
   409  
   410  This flag allows you to pass the build-time variables that are
   411  accessed like regular environment variables in the `RUN` instruction of the
   412  Dockerfile. Also, these values don't persist in the intermediate or final images
   413  like `ENV` values do.   You must add `--build-arg` for each build argument.
   414  
   415  Using this flag will not alter the output you see when the `ARG` lines from the
   416  Dockerfile are echoed during the build process.
   417  
   418  For detailed information on using `ARG` and `ENV` instructions, see the
   419  [Dockerfile reference](https://docs.docker.com/engine/reference/builder/).
   420  
   421  You may also use the `--build-arg` flag without a value, in which case the value
   422  from the local environment will be propagated into the Docker container being
   423  built:
   424  
   425  ```console
   426  $ export HTTP_PROXY=http://10.20.30.2:1234
   427  $ docker build --build-arg HTTP_PROXY .
   428  ```
   429  
   430  This is similar to how `docker run -e` works. Refer to the [`docker run` documentation](run.md#env)
   431  for more information.
   432  
   433  ### <a name="security-opt"></a> Optional security options (--security-opt)
   434  
   435  This flag is only supported on a daemon running on Windows, and only supports
   436  the `credentialspec` option. The `credentialspec` must be in the format
   437  `file://spec.txt` or `registry://keyname`.
   438  
   439  ### <a name="isolation"></a> Specify isolation technology for container (--isolation)
   440  
   441  This option is useful in situations where you are running Docker containers on
   442  Windows. The `--isolation=<value>` option sets a container's isolation
   443  technology. On Linux, the only supported is the `default` option which uses
   444  Linux namespaces. On Microsoft Windows, you can specify these values:
   445  
   446  
   447  | Value     | Description                                                                                                                                                                    |
   448  |-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
   449  | `default` | Use the value specified by the Docker daemon's `--exec-opt` . If the `daemon` does not specify an isolation technology, Microsoft Windows uses `process` as its default value. |
   450  | `process` | Namespace isolation only.                                                                                                                                                      |
   451  | `hyperv`  | Hyper-V hypervisor partition-based isolation.                                                                                                                                  |
   452  
   453  Specifying the `--isolation` flag without a value is the same as setting `--isolation="default"`.
   454  
   455  ### <a name="add-host"></a> Add entries to container hosts file (--add-host)
   456  
   457  You can add other hosts into a container's `/etc/hosts` file by using one or
   458  more `--add-host` flags. This example adds a static address for a host named
   459  `docker`:
   460  
   461      $ docker build --add-host=docker:10.180.0.1 .
   462  
   463  ### <a name="target"></a> Specifying target build stage (--target)
   464  
   465  When building a Dockerfile with multiple build stages, `--target` can be used to
   466  specify an intermediate build stage by name as a final stage for the resulting
   467  image. Commands after the target stage will be skipped.
   468  
   469  ```dockerfile
   470  FROM debian AS build-env
   471  # ...
   472  
   473  FROM alpine AS production-env
   474  # ...
   475  ```
   476  
   477  ```console
   478  $ docker build -t mybuildimage --target build-env .
   479  ```
   480  
   481  ### <a name="output"></a> Custom build outputs (--output)
   482  
   483  > **Note**
   484  >
   485  > This feature requires the BuildKit backend. You can either
   486  > [enable BuildKit](https://docs.docker.com/build/buildkit/#getting-started) or
   487  > use the [buildx](https://github.com/docker/buildx) plugin which provides more
   488  > output type options.
   489  
   490  By default, a local container image is created from the build result. The
   491  `--output` (or `-o`) flag allows you to override this behavior, and a specify a
   492  custom exporter. For example, custom exporters allow you to export the build
   493  artifacts as files on the local filesystem instead of a Docker image, which can
   494  be useful for generating local binaries, code generation etc.
   495  
   496  The value for `--output` is a CSV-formatted string defining the exporter type
   497  and options. Currently, `local` and `tar` exporters are supported. The `local`
   498  exporter writes the resulting build files to a directory on the client side. The
   499  `tar` exporter is similar but writes the files as a single tarball (`.tar`).
   500  
   501  If no type is specified, the value defaults to the output directory of the local
   502  exporter. Use a hyphen (`-`) to write the output tarball to standard output
   503  (`STDOUT`).
   504  
   505  The following example builds an image using the current directory (`.`) as build
   506  context, and exports the files to a directory named `out` in the current directory.
   507  If the directory does not exist, Docker creates the directory automatically:
   508  
   509  ```console
   510  $ docker build -o out .
   511  ```
   512  
   513  The example above uses the short-hand syntax, omitting the `type` options, and
   514  thus uses the default (`local`) exporter. The example below shows the equivalent
   515  using the long-hand CSV syntax, specifying both `type` and `dest` (destination
   516  path):
   517  
   518  ```console
   519  $ docker build --output type=local,dest=out .
   520  ```
   521  
   522  Use the `tar` type to export the files as a `.tar` archive:
   523  
   524  ```console
   525  $ docker build --output type=tar,dest=out.tar .
   526  ```
   527  
   528  The example below shows the equivalent when using the short-hand syntax. In this
   529  case, `-` is specified as destination, which automatically selects the `tar` type,
   530  and writes the output tarball to standard output, which is then redirected to
   531  the `out.tar` file:
   532  
   533  ```console
   534  $ docker build -o - . > out.tar
   535  ```
   536  
   537  The `--output` option exports all files from the target stage. A common pattern
   538  for exporting only specific files is to do multi-stage builds and to copy the
   539  desired files to a new scratch stage with [`COPY --from`](https://docs.docker.com/engine/reference/builder/#copy).
   540  
   541  The example `Dockerfile` below uses a separate stage to collect the
   542  build-artifacts for exporting:
   543  
   544  ```dockerfile
   545  FROM golang AS build-stage
   546  RUN go get -u github.com/LK4D4/vndr
   547  
   548  FROM scratch AS export-stage
   549  COPY --from=build-stage /go/bin/vndr /
   550  ```
   551  
   552  When building the Dockerfile with the `-o` option, only the files from the final
   553  stage are exported to the `out` directory, in this case, the `vndr` binary:
   554  
   555  ```console
   556  $ docker build -o out .
   557  
   558  [+] Building 2.3s (7/7) FINISHED
   559   => [internal] load build definition from Dockerfile                                                                          0.1s
   560   => => transferring dockerfile: 176B                                                                                          0.0s
   561   => [internal] load .dockerignore                                                                                             0.0s
   562   => => transferring context: 2B                                                                                               0.0s
   563   => [internal] load metadata for docker.io/library/golang:latest                                                              1.6s
   564   => [build-stage 1/2] FROM docker.io/library/golang@sha256:2df96417dca0561bf1027742dcc5b446a18957cd28eba6aa79269f23f1846d3f   0.0s
   565   => => resolve docker.io/library/golang@sha256:2df96417dca0561bf1027742dcc5b446a18957cd28eba6aa79269f23f1846d3f               0.0s
   566   => CACHED [build-stage 2/2] RUN go get -u github.com/LK4D4/vndr                                                              0.0s
   567   => [export-stage 1/1] COPY --from=build-stage /go/bin/vndr /                                                                 0.2s
   568   => exporting to client                                                                                                       0.4s
   569   => => copying files 10.30MB                                                                                                  0.3s
   570  
   571  $ ls ./out
   572  vndr
   573  ```
   574  
   575  ### <a name="cache-from"></a> Specifying external cache sources (--cache-from)
   576  
   577  > **Note**
   578  >
   579  > This feature requires the BuildKit backend. You can either
   580  > [enable BuildKit](https://docs.docker.com/build/buildkit/#getting-started) or
   581  > use the [buildx](https://github.com/docker/buildx) plugin. The previous
   582  > builder has limited support for reusing cache from pre-pulled images.
   583  
   584  In addition to local build cache, the builder can reuse the cache generated from
   585  previous builds with the `--cache-from` flag pointing to an image in the registry.
   586  
   587  To use an image as a cache source, cache metadata needs to be written into the
   588  image on creation. This can be done by setting `--build-arg BUILDKIT_INLINE_CACHE=1`
   589  when building the image. After that, the built image can be used as a cache source
   590  for subsequent builds.
   591  
   592  Upon importing the cache, the builder will only pull the JSON metadata from the
   593  registry and determine possible cache hits based on that information. If there
   594  is a cache hit, the matched layers are pulled into the local environment.
   595  
   596  In addition to images, the cache can also be pulled from special cache manifests
   597  generated by [`buildx`](https://github.com/docker/buildx) or the BuildKit CLI
   598  (`buildctl`). These manifests (when built with the `type=registry` and `mode=max`
   599  options) allow pulling layer data for intermediate stages in multi-stage builds.
   600  
   601  The following example builds an image with inline-cache metadata and pushes it
   602  to a registry, then uses the image as a cache source on another machine:
   603  
   604  ```console
   605  $ docker build -t myname/myapp --build-arg BUILDKIT_INLINE_CACHE=1 .
   606  $ docker push myname/myapp
   607  ```
   608  
   609  After pushing the image, the image is used as cache source on another machine.
   610  BuildKit automatically pulls the image from the registry if needed.
   611  
   612  On another machine:
   613  
   614  ```console
   615  $ docker build --cache-from myname/myapp .
   616  ```
   617  
   618  ### <a name="squash"></a> Squash an image's layers (--squash) (experimental)
   619  
   620  #### Overview
   621  
   622  Once the image is built, squash the new layers into a new image with a single
   623  new layer. Squashing does not destroy any existing image, rather it creates a new
   624  image with the content of the squashed layers. This effectively makes it look
   625  like all `Dockerfile` commands were created with a single layer. The build
   626  cache is preserved with this method.
   627  
   628  The `--squash` option is an experimental feature, and should not be considered
   629  stable.
   630  
   631  
   632  Squashing layers can be beneficial if your Dockerfile produces multiple layers
   633  modifying the same files, for example, files that are created in one step, and
   634  removed in another step. For other use-cases, squashing images may actually have
   635  a negative impact on performance; when pulling an image consisting of multiple
   636  layers, layers can be pulled in parallel, and allows sharing layers between
   637  images (saving space).
   638  
   639  For most use cases, multi-stage builds are a better alternative, as they give more
   640  fine-grained control over your build, and can take advantage of future
   641  optimizations in the builder. Refer to the [use multi-stage builds](https://docs.docker.com/develop/develop-images/multistage-build/)
   642  section in the userguide for more information.
   643  
   644  
   645  #### Known limitations
   646  
   647  The `--squash` option has a number of known limitations:
   648  
   649  - When squashing layers, the resulting image cannot take advantage of layer
   650    sharing with other images, and may use significantly more space. Sharing the
   651    base image is still supported.
   652  - When using this option you may see significantly more space used due to
   653    storing two copies of the image, one for the build cache with all the cache
   654    layers intact, and one for the squashed version.
   655  - While squashing layers may produce smaller images, it may have a negative
   656    impact on performance, as a single layer takes longer to extract, and
   657    downloading a single layer cannot be parallelized.
   658  - When attempting to squash an image that does not make changes to the
   659    filesystem (for example, the Dockerfile only contains `ENV` instructions),
   660    the squash step will fail (see [issue #33823](https://github.com/moby/moby/issues/33823)).
   661  
   662  #### Prerequisites
   663  
   664  The example on this page is using experimental mode in Docker 19.03.
   665  
   666  Experimental mode can be enabled by using the `--experimental` flag when starting
   667  the Docker daemon or setting `experimental: true` in the `daemon.json` configuration
   668  file.
   669  
   670  By default, experimental mode is disabled. To see the current configuration of
   671  the docker daemon, use the `docker version` command and check the `Experimental`
   672  line in the `Engine` section:
   673  
   674  ```console
   675  Client: Docker Engine - Community
   676   Version:           19.03.8
   677   API version:       1.40
   678   Go version:        go1.12.17
   679   Git commit:        afacb8b
   680   Built:             Wed Mar 11 01:21:11 2020
   681   OS/Arch:           darwin/amd64
   682   Experimental:      false
   683  
   684  Server: Docker Engine - Community
   685   Engine:
   686    Version:          19.03.8
   687    API version:      1.40 (minimum version 1.12)
   688    Go version:       go1.12.17
   689    Git commit:       afacb8b
   690    Built:            Wed Mar 11 01:29:16 2020
   691    OS/Arch:          linux/amd64
   692    Experimental:     true
   693   [...]
   694  ```
   695  
   696  To enable experimental mode, users need to restart the docker daemon with the
   697  experimental flag enabled.
   698  
   699  #### Enable Docker experimental
   700  
   701  To enable experimental features, you need to start the Docker daemon with
   702  `--experimental` flag. You can also enable the daemon flag via
   703  `/etc/docker/daemon.json`, for example:
   704  
   705  ```json
   706  {
   707      "experimental": true
   708  }
   709  ```
   710  
   711  Then make sure the experimental flag is enabled:
   712  
   713  ```console
   714  $ docker version -f '{{.Server.Experimental}}'
   715  true
   716  ```
   717  
   718  #### Build an image with `--squash` argument
   719  
   720  The following is an example of docker build with `--squash` argument
   721  
   722  ```dockerfile
   723  FROM busybox
   724  RUN echo hello > /hello
   725  RUN echo world >> /hello
   726  RUN touch remove_me /remove_me
   727  ENV HELLO=world
   728  RUN rm /remove_me
   729  ```
   730  
   731  An image named `test` is built with `--squash` argument.
   732  
   733  ```console
   734  $ docker build --squash -t test .
   735  
   736  <...>
   737  ```
   738  
   739  If everything is right, the history looks like this:
   740  
   741  ```console
   742  $ docker history test
   743  
   744  IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
   745  4e10cb5b4cac        3 seconds ago                                                       12 B                merge sha256:88a7b0112a41826885df0e7072698006ee8f621c6ab99fca7fe9151d7b599702 to sha256:47bcc53f74dc94b1920f0b34f6036096526296767650f223433fe65c35f149eb
   746  <missing>           5 minutes ago       /bin/sh -c rm /remove_me                        0 B
   747  <missing>           5 minutes ago       /bin/sh -c #(nop) ENV HELLO=world               0 B
   748  <missing>           5 minutes ago       /bin/sh -c touch remove_me /remove_me           0 B
   749  <missing>           5 minutes ago       /bin/sh -c echo world >> /hello                 0 B
   750  <missing>           6 minutes ago       /bin/sh -c echo hello > /hello                  0 B
   751  <missing>           7 weeks ago         /bin/sh -c #(nop) CMD ["sh"]                    0 B
   752  <missing>           7 weeks ago         /bin/sh -c #(nop) ADD file:47ca6e777c36a4cfff   1.113 MB
   753  ```
   754  
   755  We could find that a layer's name is `<missing>`, and there is a new layer with
   756  COMMENT `merge`.
   757  
   758  Test the image, check for `/remove_me` being gone, make sure `hello\nworld` is
   759  in `/hello`, make sure the `HELLO` environment variable's value is `world`.