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