...

Text file src/github.com/docker/cli/docs/reference/commandline/image_build.md

Documentation: github.com/docker/cli/docs/reference/commandline

     1# build
     2
     3<!---MARKER_GEN_START-->
     4Build 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
    50The `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
    53context. For example, your build can use a [*COPY*](https://docs.docker.com/reference/dockerfile/#copy)
    54instruction to reference a file in the context.
    55
    56The `URL` parameter can refer to three kinds of resources: Git repositories,
    57pre-packaged tarball contexts, and plain text files.
    58
    59### Git repositories
    60
    61When the `URL` parameter points to the location of a Git repository, the
    62repository acts as the build context. The system recursively fetches the
    63repository and its submodules. The commit history isn't preserved. A
    64repository is first pulled into a temporary directory on your local host. After
    65that succeeds, the command sends the directory to the Docker daemon as the context.
    66Local copy gives you the ability to access private repositories using local
    67user 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 using a `git clone --recursive` command.
    73
    74Git URLs accept context configuration in their fragment section, separated by a
    75colon (`:`).  The first part represents the reference that Git checks out,
    76and can be either a branch, a tag, or a remote reference. The second part
    77represents a subdirectory inside the repository used as a build
    78context.
    79
    80For 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
    87The following table represents all the valid suffixes with their build
    88contexts:
    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
   103If you pass a URL to a remote tarball, the command sends the URL itself to the
   104daemon:
   105
   106```console
   107$ docker build http://server/context.tar.gz
   108```
   109
   110The host running the Docker daemon performs the download operation,
   111which isn't necessarily the same host that issued the build command.
   112The Docker daemon fetches `context.tar.gz` and uses it as the
   113build 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
   119Instead 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
   126With PowerShell on Windows, you run:
   127
   128```powershell
   129Get-Content Dockerfile | docker build -
   130```
   131
   132If you use `STDIN` or specify a `URL` pointing to a plain text file, the daemon
   133places the contents into a `Dockerfile`, and ignores any `-f`, `--file`
   134option. In this scenario, there is no context.
   135
   136By default the `docker build` command looks for a `Dockerfile` at the root
   137of the build context. The `-f`, `--file`, option lets you specify the path to
   138an alternative file to use instead. This is useful in cases that use the same
   139set of files for multiple builds. The path must be to a file within the
   140build context. Relative path are interpreted as relative to the root of the
   141context.
   142
   143In most cases, it's best to put each Dockerfile in an empty directory. Then,
   144add to that directory only the files needed for building the Dockerfile. To
   145increase the build's performance, you can exclude files and directories by
   146adding a `.dockerignore` file to that directory as well. For information on
   147creating one, see the [.dockerignore file](https://docs.docker.com/reference/dockerfile/#dockerignore-file).
   148
   149If the Docker client loses connection to the daemon, it cancels the build.
   150This happens if you interrupt the Docker client with `CTRL-c` or if the Docker
   151client is killed for any reason. If the build initiated a pull which is still
   152running at the time the build is cancelled, the client also cancels the pull.
   153
   154## Return code
   155
   156Successful builds return exit code `0`.  When the build fails, the command
   157returns a non-zero exit code and prints an error message to `STDERR`:
   158
   159```console
   160$ docker build -t fail .
   161
   162Sending build context to Docker daemon 2.048 kB
   163Sending build context to Docker daemon
   164Step 1/3 : FROM busybox
   165 ---> 4986bf8c1536
   166Step 2/3 : RUN exit 13
   167 ---> Running in e26670ec7a0a
   168INFO[0000] The command [/bin/sh -c exit 13] returned a non-zero code: 13
   169$ echo $?
   1701
   171```
   172
   173See 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
   184Uploading context 10240 bytes
   185Step 1/3 : FROM busybox
   186Pulling repository busybox
   187 ---> e9aa60c60128MB/2.284 MB (100%) endpoint: https://cdn-registry-1.docker.io/v1/
   188Step 2/3 : RUN ls -lh /
   189 ---> Running in 9c9e81692ae9
   190total 24
   191drwxr-xr-x    2 root     root        4.0K Mar 12  2013 bin
   192drwxr-xr-x    5 root     root        4.0K Oct 19 00:19 dev
   193drwxr-xr-x    2 root     root        4.0K Oct 19 00:19 etc
   194drwxr-xr-x    2 root     root        4.0K Nov 15 23:34 lib
   195lrwxrwxrwx    1 root     root           3 Mar 12  2013 lib64 -> lib
   196dr-xr-xr-x  116 root     root           0 Nov 15 23:34 proc
   197lrwxrwxrwx    1 root     root           3 Mar 12  2013 sbin -> bin
   198dr-xr-xr-x   13 root     root           0 Nov 15 23:34 sys
   199drwxr-xr-x    2 root     root        4.0K Mar 12  2013 tmp
   200drwxr-xr-x    2 root     root        4.0K Nov 15 23:34 usr
   201 ---> b35f4035db3f
   202Step 3/3 : CMD echo Hello world
   203 ---> Running in 02071fceb21b
   204 ---> f52f38b7823e
   205Successfully built f52f38b7823e
   206Removing intermediate container 9c9e81692ae9
   207Removing intermediate container 02071fceb21b
   208```
   209
   210This example specifies that the `PATH` is `.`, and so `tar`s all the files in the
   211local directory and sends them to the Docker daemon. The `PATH` specifies
   212where to find the files for the "context" of the build on the Docker daemon.
   213Remember that the daemon could be running on a remote machine and that no
   214parsing 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
   216the ones listed to [`ADD`](https://docs.docker.com/reference/dockerfile/#add)
   217in the Dockerfile.
   218
   219The 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
   222If you wish to keep the intermediate containers after the build is complete,
   223you 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
   231This clones the GitHub repository, using the cloned repository as context,
   232and the Dockerfile at the root of the repository. You can
   233specify 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
   238Downloading context: http://server/ctx.tar.gz [===================>]    240 B/240 B
   239Step 1/3 : FROM busybox
   240 ---> 8c2e06607696
   241Step 2/3 : ADD ctx/container.cfg /
   242 ---> e7829950cee3
   243Removing intermediate container b35224abf821
   244Step 3/3 : CMD /bin/ls
   245 ---> Running in fbc63d321d73
   246 ---> 3286931702ad
   247Removing intermediate container fbc63d321d73
   248Successfully built 377c409b35e4
   249```
   250
   251This sends the URL `http://server/ctx.tar.gz` to the Docker daemon, which
   252downloads and extracts the referenced tarball. The `-f ctx/Dockerfile`
   253parameter specifies a path inside `ctx.tar.gz` to the `Dockerfile` used
   254to build the image. Any `ADD` commands in that `Dockerfile` that refer to local
   255paths must be relative to the root of the contents inside `ctx.tar.gz`. In the
   256example above, the tarball contains a directory `ctx/`, so the `ADD
   257ctx/container.cfg /` operation works as expected.
   258
   259### Build with `-`
   260
   261```console
   262$ docker build - < Dockerfile
   263```
   264
   265This example reads a Dockerfile from `STDIN` without context. Due to the lack of a
   266context, the command doesn't send contents of any local directory to the Docker daemon.
   267Since there is no context, a Dockerfile `ADD` only works if it refers to a
   268remote URL.
   269
   270```console
   271$ docker build - < context.tar.gz
   272```
   273
   274This example builds an image for a compressed context read from `STDIN`.
   275Supported formats are: `bzip2`, `gzip` and `xz`.
   276
   277### Use a .dockerignore file
   278
   279```console
   280$ docker build .
   281
   282Uploading context 18.829 MB
   283Uploading context
   284Step 1/2 : FROM busybox
   285 ---> 769b9341d937
   286Step 2/2 : CMD echo Hello world
   287 ---> Using cache
   288 ---> 99cc1ad10469
   289Successfully built 99cc1ad10469
   290$ echo ".git" > .dockerignore
   291$ docker build .
   292Uploading context  6.76 MB
   293Uploading context
   294Step 1/2 : FROM busybox
   295 ---> 769b9341d937
   296Step 2/2 : CMD echo Hello world
   297 ---> Using cache
   298 ---> 99cc1ad10469
   299Successfully built 99cc1ad10469
   300```
   301
   302This example shows the use of the `.dockerignore` file to exclude the `.git`
   303directory from the context. You can see its effect in the changed size of the
   304uploaded context. The builder reference contains detailed information on
   305[creating a .dockerignore file](https://docs.docker.com/reference/dockerfile/#dockerignore-file).
   306
   307When using the [BuildKit backend](https://docs.docker.com/build/buildkit/),
   308`docker build` searches for a `.dockerignore` file relative to the Dockerfile
   309name. For example, running `docker build -f myapp.Dockerfile .` first looks
   310for an ignore file named `myapp.Dockerfile.dockerignore`. If it can't find such a file,
   311if present, it uses the `.dockerignore` file. Using a Dockerfile based
   312`.dockerignore` is useful if a project contains multiple Dockerfiles that expect
   313to 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
   321This examples builds in the same way as the previous example, but it then tags the resulting
   322image. The repository name will be `vieux/apache` and the tag `2.0`.
   323
   324[Read more about valid tags](image_tag.md).
   325
   326You can apply multiple tags to an image. For example, you can apply the `latest`
   327tag to a newly built image and add another tag that references a specific
   328version.
   329
   330For 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
   343This uses a file called `Dockerfile.debug` for the build instructions
   344instead of `Dockerfile`.
   345
   346```console
   347$ curl example.com/remote/Dockerfile | docker build -f - .
   348```
   349
   350The above command uses the current directory as the build context and reads
   351a 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
   358The 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
   360production 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
   368These two `docker build` commands do the exact same thing. They both use the
   369contents 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
   371directory structure of the build context, regardless of how you refer to it on
   372the 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
   386When you run `docker build` with the `--cgroup-parent` option, the daemon runs the containers
   387used 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
   391Using the `--ulimit` option with `docker build` causes the daemon to start each build step's
   392container using those [`--ulimit` flag values](container_run.md#ulimit).
   393
   394### <a name="build-arg"></a> Set build-time variables (--build-arg)
   395
   396You can use `ENV` instructions in a Dockerfile to define variable values. These
   397values persist in the built image. Often persistence isn't what you want. Users
   398want to specify variables differently depending on which host they build an
   399image on.
   400
   401A good example is `http_proxy` or source versions for pulling intermediate
   402files. The `ARG` instruction lets Dockerfile authors define values that users
   403can 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
   409This flag allows you to pass the build-time variables that are
   410accessed like regular environment variables in the `RUN` instruction of the
   411Dockerfile. These values don't persist in the intermediate or final images
   412like `ENV` values do. You must add `--build-arg` for each build argument.
   413
   414Using this flag doesn't alter the output you see when the build process echoes the`ARG` lines from the
   415Dockerfile.
   416
   417For detailed information on using `ARG` and `ENV` instructions, see the
   418[Dockerfile reference](https://docs.docker.com/reference/dockerfile/).
   419
   420You can also use the `--build-arg` flag without a value, in which case the daemon
   421propagates 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
   428This example is similar to how `docker run -e` works. Refer to the [`docker run` documentation](container_run.md#env)
   429for more information.
   430
   431### <a name="security-opt"></a> Optional security options (--security-opt)
   432
   433This flag is only supported on a daemon running on Windows, and only supports
   434the `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
   439This option is useful in situations where you are running Docker containers on
   440Windows. The `--isolation=<value>` option sets a container's isolation
   441technology. On Linux, the only supported is the `default` option which uses
   442Linux 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
   451Specifying 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
   455You can add other hosts into a build container's `/etc/hosts` file by using one
   456or 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
   463If you need your build to connect to services running on the host, you can use
   464the special `host-gateway` value for `--add-host`. In the following example,
   465build 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
   471You can wrap an IPv6 address in square brackets.
   472`=` and `:` are both valid separators.
   473Both 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
   481When building a Dockerfile with multiple build stages, you can use the `--target`
   482option to specify an intermediate build stage by name as a final stage for the
   483resulting image. The daemon skips commands after the target stage.
   484
   485```dockerfile
   486FROM debian AS build-env
   487# ...
   488
   489FROM 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
   506By 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
   508custom exporter. Custom exporters allow you to export the build
   509artifacts as files on the local filesystem instead of a Docker image, which can
   510be useful for generating local binaries, code generation etc.
   511
   512The value for `--output` is a CSV-formatted string defining the exporter type
   513and options that supports `local` and `tar` exporters.
   514
   515The `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
   518If you specify no type, the value defaults to the output directory of the local
   519exporter. Use a hyphen (`-`) to write the output tarball to standard output
   520(`STDOUT`).
   521
   522The following example builds an image using the current directory (`.`) as a build
   523context, and exports the files to a directory named `out` in the current directory.
   524If the directory does not exist, Docker creates the directory automatically:
   525
   526```console
   527$ docker build -o out .
   528```
   529
   530The example above uses the short-hand syntax, omitting the `type` options, and
   531thus uses the default (`local`) exporter. The example below shows the equivalent
   532using the long-hand CSV syntax, specifying both `type` and `dest` (destination
   533path):
   534
   535```console
   536$ docker build --output type=local,dest=out .
   537```
   538
   539Use 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
   545The example below shows the equivalent when using the short-hand syntax. In this
   546case, `-` is specified as destination, which automatically selects the `tar` type,
   547and writes the output tarball to standard output, which is then redirected to
   548the `out.tar` file:
   549
   550```console
   551$ docker build -o - . > out.tar
   552```
   553
   554The `--output` option exports all files from the target stage. A common pattern
   555for exporting only specific files is to do multi-stage builds and to copy the
   556desired files to a new scratch stage with [`COPY --from`](https://docs.docker.com/reference/dockerfile/#copy).
   557
   558The example, the `Dockerfile` below uses a separate stage to collect the
   559build artifacts for exporting:
   560
   561```dockerfile
   562FROM golang AS build-stage
   563RUN go get -u github.com/LK4D4/vndr
   564
   565FROM scratch AS export-stage
   566COPY --from=build-stage /go/bin/vndr /
   567```
   568
   569When building the Dockerfile with the `-o` option, the command only exports the files from the final
   570stage 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
   589vndr
   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
   601In addition to local build cache, the builder can reuse the cache generated from
   602previous builds with the `--cache-from` flag pointing to an image in the registry.
   603
   604To use an image as a cache source, cache metadata needs to be written into the
   605image on creation. You can do this by setting `--build-arg BUILDKIT_INLINE_CACHE=1`
   606when building the image. After that, you can use the built image as a cache source
   607for subsequent builds.
   608
   609Upon importing the cache, the builder only pulls the JSON metadata from the
   610registry and determine possible cache hits based on that information. If there
   611is a cache hit, the builder pulls the matched layers into the local environment.
   612
   613In addition to images, the cache can also be pulled from special cache manifests
   614generated by [`buildx`](https://github.com/docker/buildx) or the BuildKit CLI
   615(`buildctl`). These manifests (when built with the `type=registry` and `mode=max`
   616options) allow pulling layer data for intermediate stages in multi-stage builds.
   617
   618The following example builds an image with inline-cache metadata and pushes it
   619to 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
   626After pushing the image, the image is used as cache source on another machine.
   627BuildKit automatically pulls the image from the registry if needed.
   628
   629On 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
   639Available 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
   645Find 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
   655Once the image is built, this flag squashes the new layers into a new image with
   656a single new layer. Squashing doesn't destroy any existing image, rather it
   657creates a new image with the content of the squashed layers. This effectively
   658makes it look like all `Dockerfile` commands were created with a single layer.
   659The `--squash` flag preserves the build cache.
   660
   661Squashing layers can be beneficial if your Dockerfile produces multiple layers
   662modifying the same files. For example, files created in one step and
   663removed in another step. For other use-cases, squashing images may actually have
   664a negative impact on performance. When pulling an image consisting of multiple
   665layers, the daemon can pull layers in parallel and allows sharing layers between
   666images (saving space).
   667
   668For most use cases, multi-stage builds are a better alternative, as they give more
   669fine-grained control over your build, and can take advantage of future
   670optimizations in the builder. Refer to the [Multi-stage builds](https://docs.docker.com/build/building/multi-stage/)
   671section for more information.
   672
   673#### Known limitations
   674
   675The `--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
   692The example on this page is using experimental mode in Docker 23.03.
   693
   694You can enable experimental mode by using the `--experimental` flag when starting
   695the Docker daemon or setting `experimental: true` in the `daemon.json` configuration
   696file.
   697
   698By default, experimental mode is disabled. To see the current configuration of
   699the Docker daemon, use the `docker version` command and check the `Experimental`
   700line in the `Engine` section:
   701
   702```console
   703Client: 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
   712Server: 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
   726The following is an example of a build with the `--squash` flag.  Below is the
   727`Dockerfile`:
   728
   729```dockerfile
   730FROM busybox
   731RUN echo hello > /hello
   732RUN echo world >> /hello
   733RUN touch remove_me /remove_me
   734ENV HELLO=world
   735RUN rm /remove_me
   736```
   737
   738Next, build an image named `test` using the `--squash` flag.
   739
   740```console
   741$ docker build --squash -t test .
   742```
   743
   744After the build completes, the history looks like the below. The history could show that a layer's
   745name is `<missing>`, and there is a new layer with COMMENT `merge`.
   746
   747```console
   748$ docker history test
   749
   750IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
   7514e10cb5b4cac        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
   761Test the image, check for `/remove_me` being gone, make sure `hello\nworld` is
   762in `/hello`, make sure the `HELLO` environment variable's value is `world`.

View as plain text