-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathreference.md
3026 lines (2300 loc) · 110 KB
/
reference.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: Dockerfile reference
---
Docker can build images automatically by reading the instructions from a
Dockerfile. A Dockerfile is a text document that contains all the commands a
user could call on the command line to assemble an image. This page describes
the commands you can use in a Dockerfile.
## Overview
The Dockerfile supports the following instructions:
| Instruction | Description |
| :------------------------------------- | :---------------------------------------------------------- |
| [`ADD`](#add) | Add local or remote files and directories. |
| [`ARG`](#arg) | Use build-time variables. |
| [`CMD`](#cmd) | Specify default commands. |
| [`COPY`](#copy) | Copy files and directories. |
| [`ENTRYPOINT`](#entrypoint) | Specify default executable. |
| [`ENV`](#env) | Set environment variables. |
| [`EXPOSE`](#expose) | Describe which ports your application is listening on. |
| [`FROM`](#from) | Create a new build stage from a base image. |
| [`HEALTHCHECK`](#healthcheck) | Check a container's health on startup. |
| [`LABEL`](#label) | Add metadata to an image. |
| [`MAINTAINER`](#maintainer-deprecated) | Specify the author of an image. |
| [`ONBUILD`](#onbuild) | Specify instructions for when the image is used in a build. |
| [`RUN`](#run) | Execute build commands. |
| [`SHELL`](#shell) | Set the default shell of an image. |
| [`STOPSIGNAL`](#stopsignal) | Specify the system call signal for exiting a container. |
| [`USER`](#user) | Set user and group ID. |
| [`VOLUME`](#volume) | Create volume mounts. |
| [`WORKDIR`](#workdir) | Change working directory. |
## Format
Here is the format of the Dockerfile:
```dockerfile
# Comment
INSTRUCTION arguments
```
The instruction is not case-sensitive. However, convention is for them to
be UPPERCASE to distinguish them from arguments more easily.
Docker runs instructions in a Dockerfile in order. A Dockerfile **must
begin with a `FROM` instruction**. This may be after [parser
directives](#parser-directives), [comments](#format), and globally scoped
[ARGs](#arg). The `FROM` instruction specifies the [base
image](https://docs.docker.com/glossary/#base-image) from which you are
building. `FROM` may only be preceded by one or more `ARG` instructions, which
declare arguments that are used in `FROM` lines in the Dockerfile.
BuildKit treats lines that begin with `#` as a comment, unless the line is
a valid [parser directive](#parser-directives). A `#` marker anywhere
else in a line is treated as an argument. This allows statements like:
```dockerfile
# Comment
RUN echo 'we are running some # of cool things'
```
Comment lines are removed before the Dockerfile instructions are executed.
The comment in the following example is removed before the shell executes
the `echo` command.
```dockerfile
RUN echo hello \
# comment
world
```
The following examples is equivalent.
```dockerfile
RUN echo hello \
world
```
Comments don't support line continuation characters.
> [!NOTE]
> **Note on whitespace**
>
> For backward compatibility, leading whitespace before comments (`#`) and
> instructions (such as `RUN`) are ignored, but discouraged. Leading whitespace
> is not preserved in these cases, and the following examples are therefore
> equivalent:
>
> ```dockerfile
> # this is a comment-line
> RUN echo hello
> RUN echo world
> ```
>
> ```dockerfile
> # this is a comment-line
> RUN echo hello
> RUN echo world
> ```
>
> Whitespace in instruction arguments, however, isn't ignored.
> The following example prints ` hello world`
> with leading whitespace as specified:
>
> ```dockerfile
> RUN echo "\
> hello\
> world"
> ```
## Parser directives
Parser directives are optional, and affect the way in which subsequent lines
in a Dockerfile are handled. Parser directives don't add layers to the build,
and don't show up as build steps. Parser directives are written as a
special type of comment in the form `# directive=value`. A single directive
may only be used once.
The following parser directives are supported:
- [`syntax`](#syntax)
- [`escape`](#escape)
- [`check`](#check) (since Dockerfile v1.8.0)
Once a comment, empty line or builder instruction has been processed, BuildKit
no longer looks for parser directives. Instead it treats anything formatted
as a parser directive as a comment and doesn't attempt to validate if it might
be a parser directive. Therefore, all parser directives must be at the
top of a Dockerfile.
Parser directive keys, such as `syntax` or `check`, aren't case-sensitive, but
they're lowercase by convention. Values for a directive are case-sensitive and
must be written in the appropriate case for the directive. For example,
`#check=skip=jsonargsrecommended` is invalid because the check name must use
Pascal case, not lowercase. It's also conventional to include a blank line
following any parser directives. Line continuation characters aren't supported
in parser directives.
Due to these rules, the following examples are all invalid:
Invalid due to line continuation:
```dockerfile
# direc \
tive=value
```
Invalid due to appearing twice:
```dockerfile
# directive=value1
# directive=value2
FROM ImageName
```
Treated as a comment because it appears after a builder instruction:
```dockerfile
FROM ImageName
# directive=value
```
Treated as a comment because it appears after a comment that isn't a parser
directive:
```dockerfile
# About my dockerfile
# directive=value
FROM ImageName
```
The following `unknowndirective` is treated as a comment because it isn't
recognized. The known `syntax` directive is treated as a comment because it
appears after a comment that isn't a parser directive.
```dockerfile
# unknowndirective=value
# syntax=value
```
Non line-breaking whitespace is permitted in a parser directive. Hence, the
following lines are all treated identically:
```dockerfile
#directive=value
# directive =value
# directive= value
# directive = value
# dIrEcTiVe=value
```
### syntax
<a name="external-implementation-features"><!-- included for deep-links to old section --></a>
Use the `syntax` parser directive to declare the Dockerfile syntax version to
use for the build. If unspecified, BuildKit uses a bundled version of the
Dockerfile frontend. Declaring a syntax version lets you automatically use the
latest Dockerfile version without having to upgrade BuildKit or Docker Engine,
or even use a custom Dockerfile implementation.
Most users will want to set this parser directive to `docker/dockerfile:1`,
which causes BuildKit to pull the latest stable version of the Dockerfile
syntax before the build.
```dockerfile
# syntax=docker/dockerfile:1
```
For more information about how the parser directive works, see
[Custom Dockerfile syntax](https://docs.docker.com/build/buildkit/dockerfile-frontend/).
### escape
```dockerfile
# escape=\
```
Or
```dockerfile
# escape=`
```
The `escape` directive sets the character used to escape characters in a
Dockerfile. If not specified, the default escape character is `\`.
The escape character is used both to escape characters in a line, and to
escape a newline. This allows a Dockerfile instruction to
span multiple lines. Note that regardless of whether the `escape` parser
directive is included in a Dockerfile, escaping is not performed in
a `RUN` command, except at the end of a line.
Setting the escape character to `` ` `` is especially useful on
`Windows`, where `\` is the directory path separator. `` ` `` is consistent
with [Windows PowerShell](https://technet.microsoft.com/en-us/library/hh847755.aspx).
Consider the following example which would fail in a non-obvious way on
Windows. The second `\` at the end of the second line would be interpreted as an
escape for the newline, instead of a target of the escape from the first `\`.
Similarly, the `\` at the end of the third line would, assuming it was actually
handled as an instruction, cause it be treated as a line continuation. The result
of this Dockerfile is that second and third lines are considered a single
instruction:
```dockerfile
FROM microsoft/nanoserver
COPY testfile.txt c:\\
RUN dir c:\
```
Results in:
```console
PS E:\myproject> docker build -t cmd .
Sending build context to Docker daemon 3.072 kB
Step 1/2 : FROM microsoft/nanoserver
---> 22738ff49c6d
Step 2/2 : COPY testfile.txt c:\RUN dir c:
GetFileAttributesEx c:RUN: The system cannot find the file specified.
PS E:\myproject>
```
One solution to the above would be to use `/` as the target of both the `COPY`
instruction, and `dir`. However, this syntax is, at best, confusing as it is not
natural for paths on Windows, and at worst, error prone as not all commands on
Windows support `/` as the path separator.
By adding the `escape` parser directive, the following Dockerfile succeeds as
expected with the use of natural platform semantics for file paths on Windows:
```dockerfile
# escape=`
FROM microsoft/nanoserver
COPY testfile.txt c:\
RUN dir c:\
```
Results in:
```console
PS E:\myproject> docker build -t succeeds --no-cache=true .
Sending build context to Docker daemon 3.072 kB
Step 1/3 : FROM microsoft/nanoserver
---> 22738ff49c6d
Step 2/3 : COPY testfile.txt c:\
---> 96655de338de
Removing intermediate container 4db9acbb1682
Step 3/3 : RUN dir c:\
---> Running in a2c157f842f5
Volume in drive C has no label.
Volume Serial Number is 7E6D-E0F7
Directory of c:\
10/05/2016 05:04 PM 1,894 License.txt
10/05/2016 02:22 PM <DIR> Program Files
10/05/2016 02:14 PM <DIR> Program Files (x86)
10/28/2016 11:18 AM 62 testfile.txt
10/28/2016 11:20 AM <DIR> Users
10/28/2016 11:20 AM <DIR> Windows
2 File(s) 1,956 bytes
4 Dir(s) 21,259,096,064 bytes free
---> 01c7f3bef04f
Removing intermediate container a2c157f842f5
Successfully built 01c7f3bef04f
PS E:\myproject>
```
### check
```dockerfile
# check=skip=<checks|all>
# check=error=<boolean>
```
The `check` directive is used to configure how [build checks](https://docs.docker.com/build/checks/)
are evaluated. By default, all checks are run, and failures are treated as
warnings.
You can disable specific checks using `#check=skip=<check-name>`. To specify
multiple checks to skip, separate them with a comma:
```dockerfile
# check=skip=JSONArgsRecommended,StageNameCasing
```
To disable all checks, use `#check=skip=all`.
By default, builds with failing build checks exit with a zero status code
despite warnings. To make the build fail on warnings, set `#check=error=true`.
```dockerfile
# check=error=true
```
> [!NOTE]
> When using the `check` directive, with `error=true` option, it is recommended
> to pin the [Dockerfile syntax](#syntax) to a specific version. Otherwise, your build may
> start to fail when new checks are added in the future versions.
To combine both the `skip` and `error` options, use a semi-colon to separate
them:
```dockerfile
# check=skip=JSONArgsRecommended;error=true
```
To see all available checks, see the [build checks reference](https://docs.docker.com/reference/build-checks/).
Note that the checks available depend on the Dockerfile syntax version. To make
sure you're getting the most up-to-date checks, use the [`syntax`](#syntax)
directive to specify the Dockerfile syntax version to the latest stable
version.
## Environment replacement
Environment variables (declared with [the `ENV` statement](#env)) can also be
used in certain instructions as variables to be interpreted by the
Dockerfile. Escapes are also handled for including variable-like syntax
into a statement literally.
Environment variables are notated in the Dockerfile either with
`$variable_name` or `${variable_name}`. They are treated equivalently and the
brace syntax is typically used to address issues with variable names with no
whitespace, like `${foo}_bar`.
The `${variable_name}` syntax also supports a few of the standard `bash`
modifiers as specified below:
- `${variable:-word}` indicates that if `variable` is set then the result
will be that value. If `variable` is not set then `word` will be the result.
- `${variable:+word}` indicates that if `variable` is set then `word` will be
the result, otherwise the result is the empty string.
The following variable replacements are supported in a pre-release version of
Dockerfile syntax, when using the `# syntax=docker/dockerfile-upstream:master` syntax
directive in your Dockerfile:
- `${variable#pattern}` removes the shortest match of `pattern` from `variable`,
seeking from the start of the string.
```bash
str=foobarbaz echo ${str#f*b} # arbaz
```
- `${variable##pattern}` removes the longest match of `pattern` from `variable`,
seeking from the start of the string.
```bash
str=foobarbaz echo ${str##f*b} # az
```
- `${variable%pattern}` removes the shortest match of `pattern` from `variable`,
seeking backwards from the end of the string.
```bash
string=foobarbaz echo ${string%b*} # foobar
```
- `${variable%%pattern}` removes the longest match of `pattern` from `variable`,
seeking backwards from the end of the string.
```bash
string=foobarbaz echo ${string%%b*} # foo
```
- `${variable/pattern/replacement}` replace the first occurrence of `pattern`
in `variable` with `replacement`
```bash
string=foobarbaz echo ${string/ba/fo} # fooforbaz
```
- `${variable//pattern/replacement}` replaces all occurrences of `pattern`
in `variable` with `replacement`
```bash
string=foobarbaz echo ${string//ba/fo} # fooforfoz
```
In all cases, `word` can be any string, including additional environment
variables.
`pattern` is a glob pattern where `?` matches any single character
and `*` any number of characters (including zero). To match literal `?` and `*`,
use a backslash escape: `\?` and `\*`.
You can escape whole variable names by adding a `\` before the variable: `\$foo` or `\${foo}`,
for example, will translate to `$foo` and `${foo}` literals respectively.
Example (parsed representation is displayed after the `#`):
```dockerfile
FROM busybox
ENV FOO=/bar
WORKDIR ${FOO} # WORKDIR /bar
ADD . $FOO # ADD . /bar
COPY \$FOO /quux # COPY $FOO /quux
```
Environment variables are supported by the following list of instructions in
the Dockerfile:
- `ADD`
- `COPY`
- `ENV`
- `EXPOSE`
- `FROM`
- `LABEL`
- `STOPSIGNAL`
- `USER`
- `VOLUME`
- `WORKDIR`
- `ONBUILD` (when combined with one of the supported instructions above)
You can also use environment variables with `RUN`, `CMD`, and `ENTRYPOINT`
instructions, but in those cases the variable substitution is handled by the
command shell, not the builder. Note that instructions using the exec form
don't invoke a command shell automatically. See [Variable
substitution](#variable-substitution).
Environment variable substitution use the same value for each variable
throughout the entire instruction. Changing the value of a variable only takes
effect in subsequent instructions. Consider the following example:
```dockerfile
ENV abc=hello
ENV abc=bye def=$abc
ENV ghi=$abc
```
- The value of `def` becomes `hello`
- The value of `ghi` becomes `bye`
## .dockerignore file
You can use `.dockerignore` file to exclude files and directories from the
build context. For more information, see
[.dockerignore file](https://docs.docker.com/build/building/context/#dockerignore-files).
## Shell and exec form
The `RUN`, `CMD`, and `ENTRYPOINT` instructions all have two possible forms:
- `INSTRUCTION ["executable","param1","param2"]` (exec form)
- `INSTRUCTION command param1 param2` (shell form)
The exec form makes it possible to avoid shell string munging, and to invoke
commands using a specific command shell, or any other executable. It uses a
JSON array syntax, where each element in the array is a command, flag, or
argument.
The shell form is more relaxed, and emphasizes ease of use, flexibility, and
readability. The shell form automatically uses a command shell, whereas the
exec form does not.
### Exec form
The exec form is parsed as a JSON array, which means that
you must use double-quotes (") around words, not single-quotes (').
```dockerfile
ENTRYPOINT ["/bin/bash", "-c", "echo hello"]
```
The exec form is best used to specify an `ENTRYPOINT` instruction, combined
with `CMD` for setting default arguments that can be overridden at runtime. For
more information, see [ENTRYPOINT](#entrypoint).
#### Variable substitution
Using the exec form doesn't automatically invoke a command shell. This means
that normal shell processing, such as variable substitution, doesn't happen.
For example, `RUN [ "echo", "$HOME" ]` won't handle variable substitution for
`$HOME`.
If you want shell processing then either use the shell form or execute a shell
directly with the exec form, for example: `RUN [ "sh", "-c", "echo $HOME" ]`.
When using the exec form and executing a shell directly, as in the case for the
shell form, it's the shell that's doing the environment variable substitution,
not the builder.
#### Backslashes
In exec form, you must escape backslashes. This is particularly relevant on
Windows where the backslash is the path separator. The following line would
otherwise be treated as shell form due to not being valid JSON, and fail in an
unexpected way:
```dockerfile
RUN ["c:\windows\system32\tasklist.exe"]
```
The correct syntax for this example is:
```dockerfile
RUN ["c:\\windows\\system32\\tasklist.exe"]
```
### Shell form
Unlike the exec form, instructions using the shell form always use a command
shell. The shell form doesn't use the JSON array format, instead it's a regular
string. The shell form string lets you escape newlines using the [escape
character](#escape) (backslash by default) to continue a single instruction
onto the next line. This makes it easier to use with longer commands, because
it lets you split them up into multiple lines. For example, consider these two
lines:
```dockerfile
RUN source $HOME/.bashrc && \
echo $HOME
```
They're equivalent to the following line:
```dockerfile
RUN source $HOME/.bashrc && echo $HOME
```
You can also use heredocs with the shell form to break up supported commands.
```dockerfile
RUN <<EOF
source $HOME/.bashrc && \
echo $HOME
EOF
```
For more information about heredocs, see [Here-documents](#here-documents).
### Use a different shell
You can change the default shell using the `SHELL` command. For example:
```dockerfile
SHELL ["/bin/bash", "-c"]
RUN echo hello
```
For more information, see [SHELL](#shell).
## FROM
```dockerfile
FROM [--platform=<platform>] <image> [AS <name>]
```
Or
```dockerfile
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]
```
Or
```dockerfile
FROM [--platform=<platform>] <image>[@<digest>] [AS <name>]
```
The `FROM` instruction initializes a new build stage and sets the
[base image](https://docs.docker.com/glossary/#base-image) for subsequent
instructions. As such, a valid Dockerfile must start with a `FROM` instruction.
The image can be any valid image.
- `ARG` is the only instruction that may precede `FROM` in the Dockerfile.
See [Understand how ARG and FROM interact](#understand-how-arg-and-from-interact).
- `FROM` can appear multiple times within a single Dockerfile to
create multiple images or use one build stage as a dependency for another.
Simply make a note of the last image ID output by the commit before each new
`FROM` instruction. Each `FROM` instruction clears any state created by previous
instructions.
- Optionally a name can be given to a new build stage by adding `AS name` to the
`FROM` instruction. The name can be used in subsequent `FROM <name>`,
[`COPY --from=<name>`](#copy---from),
and [`RUN --mount=type=bind,from=<name>`](#run---mounttypebind) instructions
to refer to the image built in this stage.
- The `tag` or `digest` values are optional. If you omit either of them, the
builder assumes a `latest` tag by default. The builder returns an error if it
can't find the `tag` value.
The optional `--platform` flag can be used to specify the platform of the image
in case `FROM` references a multi-platform image. For example, `linux/amd64`,
`linux/arm64`, or `windows/amd64`. By default, the target platform of the build
request is used. Global build arguments can be used in the value of this flag,
for example [automatic platform ARGs](#automatic-platform-args-in-the-global-scope)
allow you to force a stage to native build platform (`--platform=$BUILDPLATFORM`),
and use it to cross-compile to the target platform inside the stage.
### Understand how ARG and FROM interact
`FROM` instructions support variables that are declared by any `ARG`
instructions that occur before the first `FROM`.
```dockerfile
ARG CODE_VERSION=latest
FROM base:${CODE_VERSION}
CMD /code/run-app
FROM extras:${CODE_VERSION}
CMD /code/run-extras
```
An `ARG` declared before a `FROM` is outside of a build stage, so it
can't be used in any instruction after a `FROM`. To use the default value of
an `ARG` declared before the first `FROM` use an `ARG` instruction without
a value inside of a build stage:
```dockerfile
ARG VERSION=latest
FROM busybox:$VERSION
ARG VERSION
RUN echo $VERSION > image_version
```
## RUN
The `RUN` instruction will execute any commands to create a new layer on top of
the current image. The added layer is used in the next step in the Dockerfile.
`RUN` has two forms:
```dockerfile
# Shell form:
RUN [OPTIONS] <command> ...
# Exec form:
RUN [OPTIONS] [ "<command>", ... ]
```
For more information about the differences between these two forms, see
[shell or exec forms](#shell-and-exec-form).
The shell form is most commonly used, and lets you break up longer
instructions into multiple lines, either using newline [escapes](#escape), or
with [heredocs](#here-documents):
```dockerfile
RUN <<EOF
apt-get update
apt-get install -y curl
EOF
```
The available `[OPTIONS]` for the `RUN` instruction are:
| Option | Minimum Dockerfile version |
| ------------------------------- | -------------------------- |
| [`--mount`](#run---mount) | 1.2 |
| [`--network`](#run---network) | 1.3 |
| [`--security`](#run---security) | 1.1.2-labs |
### Cache invalidation for RUN instructions
The cache for `RUN` instructions isn't invalidated automatically during
the next build. The cache for an instruction like
`RUN apt-get dist-upgrade -y` will be reused during the next build. The
cache for `RUN` instructions can be invalidated by using the `--no-cache`
flag, for example `docker build --no-cache`.
See the [Dockerfile Best Practices
guide](https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/) for more information.
The cache for `RUN` instructions can be invalidated by [`ADD`](#add) and [`COPY`](#copy) instructions.
### RUN --mount
```dockerfile
RUN --mount=[type=<TYPE>][,option=<value>[,option=<value>]...]
```
`RUN --mount` allows you to create filesystem mounts that the build can access.
This can be used to:
- Create bind mount to the host filesystem or other build stages
- Access build secrets or ssh-agent sockets
- Use a persistent package management cache to speed up your build
The supported mount types are:
| Type | Description |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| [`bind`](#run---mounttypebind) (default) | Bind-mount context directories (read-only). |
| [`cache`](#run---mounttypecache) | Mount a temporary directory to cache directories for compilers and package managers. |
| [`tmpfs`](#run---mounttypetmpfs) | Mount a `tmpfs` in the build container. |
| [`secret`](#run---mounttypesecret) | Allow the build container to access secure files such as private keys without baking them into the image or build cache. |
| [`ssh`](#run---mounttypessh) | Allow the build container to access SSH keys via SSH agents, with support for passphrases. |
### RUN --mount=type=bind
This mount type allows binding files or directories to the build container. A
bind mount is read-only by default.
| Option | Description |
| ---------------------------------- | ---------------------------------------------------------------------------------------------- |
| `target`, `dst`, `destination`[^1] | Mount path. |
| `source` | Source path in the `from`. Defaults to the root of the `from`. |
| `from` | Build stage, context, or image name for the root of the source. Defaults to the build context. |
| `rw`,`readwrite` | Allow writes on the mount. Written data will be discarded. |
### RUN --mount=type=cache
This mount type allows the build container to cache directories for compilers
and package managers.
| Option | Description |
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | Optional ID to identify separate/different caches. Defaults to value of `target`. |
| `target`, `dst`, `destination`[^1] | Mount path. |
| `ro`,`readonly` | Read-only if set. |
| `sharing` | One of `shared`, `private`, or `locked`. Defaults to `shared`. A `shared` cache mount can be used concurrently by multiple writers. `private` creates a new mount if there are multiple writers. `locked` pauses the second writer until the first one releases the mount. |
| `from` | Build stage, context, or image name to use as a base of the cache mount. Defaults to empty directory. |
| `source` | Subpath in the `from` to mount. Defaults to the root of the `from`. |
| `mode` | File mode for new cache directory in octal. Default `0755`. |
| `uid` | User ID for new cache directory. Default `0`. |
| `gid` | Group ID for new cache directory. Default `0`. |
Contents of the cache directories persists between builder invocations without
invalidating the instruction cache. Cache mounts should only be used for better
performance. Your build should work with any contents of the cache directory as
another build may overwrite the files or GC may clean it if more storage space
is needed.
#### Example: cache Go packages
```dockerfile
# syntax=docker/dockerfile:1
FROM golang
RUN --mount=type=cache,target=/root/.cache/go-build \
go build ...
```
#### Example: cache apt packages
```dockerfile
# syntax=docker/dockerfile:1
FROM ubuntu
RUN rm -f /etc/apt/apt.conf.d/docker-clean; echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt,sharing=locked \
apt update && apt-get --no-install-recommends install -y gcc
```
Apt needs exclusive access to its data, so the caches use the option
`sharing=locked`, which will make sure multiple parallel builds using
the same cache mount will wait for each other and not access the same
cache files at the same time. You could also use `sharing=private` if
you prefer to have each build create another cache directory in this
case.
### RUN --mount=type=tmpfs
This mount type allows mounting `tmpfs` in the build container.
| Option | Description |
| ---------------------------------- | ----------------------------------------------------- |
| `target`, `dst`, `destination`[^1] | Mount path. |
| `size` | Specify an upper limit on the size of the filesystem. |
### RUN --mount=type=secret
This mount type allows the build container to access secret values, such as
tokens or private keys, without baking them into the image.
By default, the secret is mounted as a file. You can also mount the secret as
an environment variable by setting the `env` option.
| Option | Description |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------- |
| `id` | ID of the secret. Defaults to basename of the target path. |
| `target`, `dst`, `destination` | Mount the secret to the specified path. Defaults to `/run/secrets/` + `id` if unset and if `env` is also unset. |
| `env` | Mount the secret to an environment variable instead of a file, or both. (since Dockerfile v1.10.0) |
| `required` | If set to `true`, the instruction errors out when the secret is unavailable. Defaults to `false`. |
| `mode` | File mode for secret file in octal. Default `0400`. |
| `uid` | User ID for secret file. Default `0`. |
| `gid` | Group ID for secret file. Default `0`. |
#### Example: access to S3
```dockerfile
# syntax=docker/dockerfile:1
FROM python:3
RUN pip install awscli
RUN --mount=type=secret,id=aws,target=/root/.aws/credentials \
aws s3 cp s3://... ...
```
```console
$ docker buildx build --secret id=aws,src=$HOME/.aws/credentials .
```
#### Example: Mount as environment variable
The following example takes the secret `API_KEY` and mounts it as an
environment variable with the same name.
```dockerfile
# syntax=docker/dockerfile:1
FROM alpine
RUN --mount=type=secret,id=API_KEY,env=API_KEY \
some-command --token-from-env $API_KEY
```
Assuming that the `API_KEY` environment variable is set in the build
environment, you can build this with the following command:
```console
$ docker buildx build --secret id=API_KEY .
```
### RUN --mount=type=ssh
This mount type allows the build container to access SSH keys via SSH agents,
with support for passphrases.
| Option | Description |
| ------------------------------ | ---------------------------------------------------------------------------------------------- |
| `id` | ID of SSH agent socket or key. Defaults to "default". |
| `target`, `dst`, `destination` | SSH agent socket path. Defaults to `/run/buildkit/ssh_agent.${N}`. |
| `required` | If set to `true`, the instruction errors out when the key is unavailable. Defaults to `false`. |
| `mode` | File mode for socket in octal. Default `0600`. |
| `uid` | User ID for socket. Default `0`. |
| `gid` | Group ID for socket. Default `0`. |
#### Example: access to GitLab
```dockerfile
# syntax=docker/dockerfile:1
FROM alpine
RUN apk add --no-cache openssh-client
RUN mkdir -p -m 0700 ~/.ssh && ssh-keyscan gitlab.com >> ~/.ssh/known_hosts
RUN --mount=type=ssh \
ssh -q -T [email protected] 2>&1 | tee /hello
# "Welcome to GitLab, @GITLAB_USERNAME_ASSOCIATED_WITH_SSHKEY" should be printed here
# with the type of build progress is defined as `plain`.
```
```console
$ eval $(ssh-agent)
$ ssh-add ~/.ssh/id_rsa
(Input your passphrase here)
$ docker buildx build --ssh default=$SSH_AUTH_SOCK .
```
You can also specify a path to `*.pem` file on the host directly instead of `$SSH_AUTH_SOCK`.
However, pem files with passphrases are not supported.
### RUN --network
```dockerfile
RUN --network=<TYPE>
```
`RUN --network` allows control over which networking environment the command
is run in.
The supported network types are:
| Type | Description |
| -------------------------------------------- | -------------------------------------- |
| [`default`](#run---networkdefault) (default) | Run in the default network. |
| [`none`](#run---networknone) | Run with no network access. |
| [`host`](#run---networkhost) | Run in the host's network environment. |
### RUN --network=default
Equivalent to not supplying a flag at all, the command is run in the default
network for the build.
### RUN --network=none
The command is run with no network access (`lo` is still available, but is
isolated to this process)
#### Example: isolating external effects
```dockerfile
# syntax=docker/dockerfile:1
FROM python:3.6
ADD mypackage.tgz wheels/
RUN --network=none pip install --find-links wheels mypackage
```
`pip` will only be able to install the packages provided in the tarfile, which
can be controlled by an earlier build stage.
### RUN --network=host
The command is run in the host's network environment (similar to
`docker build --network=host`, but on a per-instruction basis)
> [!WARNING]
> The use of `--network=host` is protected by the `network.host` entitlement,
> which needs to be enabled when starting the buildkitd daemon with
> `--allow-insecure-entitlement network.host` flag or in [buildkitd config](https://github.com/moby/buildkit/blob/master/docs/buildkitd.toml.md),
> and for a build request with [`--allow network.host` flag](https://docs.docker.com/engine/reference/commandline/buildx_build/#allow).
### RUN --security
> [!NOTE]
> Not yet available in stable syntax, use [`docker/dockerfile:1-labs`](#syntax) version.
```dockerfile
RUN --security=<sandbox|insecure>
```
The default security mode is `sandbox`.
With `--security=insecure`, the builder runs the command without sandbox in insecure
mode, which allows to run flows requiring elevated privileges (e.g. containerd).
This is equivalent to running `docker run --privileged`.
> [!WARNING]
> In order to access this feature, entitlement `security.insecure` should be
> enabled when starting the buildkitd daemon with
> `--allow-insecure-entitlement security.insecure` flag or in [buildkitd config](https://github.com/moby/buildkit/blob/master/docs/buildkitd.toml.md),
> and for a build request with [`--allow security.insecure` flag](https://docs.docker.com/engine/reference/commandline/buildx_build/#allow).
Default sandbox mode can be activated via `--security=sandbox`, but that is no-op.
#### Example: check entitlements
```dockerfile
# syntax=docker/dockerfile:1-labs
FROM ubuntu
RUN --security=insecure cat /proc/self/status | grep CapEff
```
```text
#84 0.093 CapEff: 0000003fffffffff
```
## CMD
The `CMD` instruction sets the command to be executed when running a container
from an image.
You can specify `CMD` instructions using
[shell or exec forms](#shell-and-exec-form):
- `CMD ["executable","param1","param2"]` (exec form)
- `CMD ["param1","param2"]` (exec form, as default parameters to `ENTRYPOINT`)
- `CMD command param1 param2` (shell form)
There can only be one `CMD` instruction in a Dockerfile. If you list more than
one `CMD`, only the last one takes effect.
The purpose of a `CMD` is to provide defaults for an executing container. These
defaults can include an executable, or they can omit the executable, in which
case you must specify an `ENTRYPOINT` instruction as well.
If you would like your container to run the same executable every time, then
you should consider using `ENTRYPOINT` in combination with `CMD`. See
[`ENTRYPOINT`](#entrypoint). If the user specifies arguments to `docker run`
then they will override the default specified in `CMD`, but still use the
default `ENTRYPOINT`.