docker 最新Dockerfile命令手册

2023-05-16

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 you would normally execute manually in order to build a Docker image. By calling docker build from your terminal, you can have Docker build your image step by step, executing the instructions successively.

This page discusses the specifics of all the instructions you can use in your Dockerfile. To further help you write a clear, readable, maintainable Dockerfile, we've also written a Dockerfile Best Practices guide. Lastly, you can test your Dockerfile knowledge with the Dockerfile tutorial.

Usage

To build an image from a source repository, create a description file called Dockerfile at the root of your repository. This file will describe the steps to assemble the image.

Then call docker build with the path of your source repository as the argument (for example, .):

$ sudo docker build .

The path to the source repository defines where to find the context of the build. The build is run by the Docker daemon, not by the CLI, so the whole context must be transferred to the daemon. The Docker CLI reports "Sending build context to Docker daemon" when the context is sent to the daemon.

Warning Avoid using your root directory, /, as the root of the source repository. The docker buildcommand will use whatever directory contains the Dockerfile as the build context (including all of its subdirectories). The build context will be sent to the Docker daemon before building the image, which means if you use / as the source repository, the entire contents of your hard drive will get sent to the daemon (and thus to the machine running the daemon). You probably don't want that.

In most cases, it's best to put each Dockerfile in an empty directory, and then add only the files needed for building that Dockerfile to that directory. To further speed up the build, you can exclude files and directories by adding a .dockerignore file to the same directory.

You can specify a repository and tag at which to save the new image if the build succeeds:

$ sudo docker build -t shykes/myapp .

The Docker daemon will run your steps one-by-one, committing the result to a new image if necessary, before finally outputting the ID of your new image. The Docker daemon will automatically clean up the context you sent.

Note that each instruction is run independently, and causes a new image to be created - so RUN cd /tmp will not have any effect on the next instructions.

Whenever possible, Docker will re-use the intermediate images, accelerating docker build significantly (indicated by Using cache - see the Dockerfile Best Practices guide for more information):

$ sudo docker build -t SvenDowideit/ambassador .
Uploading context 10.24 kB
Uploading context
Step 1 : FROM docker-ut
 ---> cbba202fe96b
Step 2 : MAINTAINER SvenDowideit@home.org.au
 ---> Using cache
 ---> 51182097be13
Step 3 : CMD env | grep _TCP= | sed 's/.*_PORT_\([0-9]*\)_TCP=tcp:\/\/\(.*\):\(.*\)/socat TCP4-LISTEN:\1,fork,reuseaddr TCP4:\2:\3 \&/'  | sh && top
 ---> Using cache
 ---> 1a5ffc17324d
Successfully built 1a5ffc17324d

When you're done with your build, you're ready to look into Pushing a repository to its registry.

Format

Here is the format of the Dockerfile:

# Comment
INSTRUCTION arguments

The Instruction is not case-sensitive, however convention is for them to be UPPERCASE in order to distinguish them from arguments more easily.

Docker runs the instructions in a Dockerfile in order. The first instruction must be `FROM` in order to specify the Base Image from which you are building.

Docker will treat lines that begin with # as a comment. A # marker anywhere else in the line will be treated as an argument. This allows statements like:

# Comment
RUN echo 'we are running some # of cool things'

Here is the set of instructions you can use in a Dockerfile for building images.

Environment Replacement

Note: prior to 1.3, Dockerfile environment variables were handled similarly, in that they would be replaced as described below. However, there was no formal definition on as to which instructions handled environment replacement at the time. After 1.3 this behavior will be preserved and canonical.

Environment variables (declared with the ENV statement) 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.

Escaping is possible 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 #):

FROM busybox
ENV foo /bar
WORKDIR ${foo}   # WORKDIR /bar
ADD . $foo       # ADD . /bar
COPY \$foo /quux # COPY $foo /quux

The instructions that handle environment variables in the Dockerfile are:

  • ENV
  • ADD
  • COPY
  • WORKDIR
  • EXPOSE
  • VOLUME
  • USER

ONBUILD instructions are NOT supported for environment replacement, even the instructions above.

The .dockerignore file

If a file named .dockerignore exists in the source repository, then it is interpreted as a newline-separated list of exclusion patterns. Exclusion patterns match files or directories relative to the source repository that will be excluded from the context. Globbing is done using Go's filepath.Match rules.

Note: The .dockerignore file can even be used to ignore the Dockerfile and .dockerignore files. This might be useful if you are copying files from the root of the build context into your new containter but do not want to include the Dockerfile or .dockerignore files (e.g. ADD . /someDir/).

The following example shows the use of the .dockerignore file to exclude the .git directory from the context. Its effect can be seen in the changed size of the uploaded context.

$ sudo docker build .
Uploading context 18.829 MB
Uploading context
Step 0 : FROM busybox
 ---> 769b9341d937
Step 1 : CMD echo Hello World
 ---> Using cache
 ---> 99cc1ad10469
Successfully built 99cc1ad10469
$ echo ".git" > .dockerignore
$ sudo docker build .
Uploading context  6.76 MB
Uploading context
Step 0 : FROM busybox
 ---> 769b9341d937
Step 1 : CMD echo Hello World
 ---> Using cache
 ---> 99cc1ad10469
Successfully built 99cc1ad10469

FROM

FROM <image>

Or

FROM <image>:<tag>

The FROM instruction sets the Base Image for subsequent instructions. As such, a valid Dockerfile must have FROM as its first instruction. The image can be any valid image – it is especially easy to start by pulling an image from the Public Repositories.

FROM must be the first non-comment instruction in the Dockerfile.

FROM can appear multiple times within a single Dockerfile in order to create multiple images. Simply make a note of the last image ID output by the commit before each new FROM command.

If no tag is given to the FROM instruction, latest is assumed. If the used tag does not exist, an error will be returned.

MAINTAINER

MAINTAINER <name>

The MAINTAINER instruction allows you to set the Author field of the generated images.

RUN

RUN has 2 forms:

  • RUN <command> (the command is run in a shell - /bin/sh -c - shell form)
  • RUN ["executable", "param1", "param2"] (exec form)

The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile.

Layering RUN instructions and generating commits conforms to the core concepts of Docker where commits are cheap and containers can be created from any point in an image's history, much like source control.

The exec form makes it possible to avoid shell string munging, and to RUN commands using a base image that does not contain /bin/sh.

Note: To use a different shell, other than '/bin/sh', use the exec form passing in the desired shell. For example, RUN ["/bin/bash", "-c", "echo hello"]

Note: The exec form is parsed as a JSON array, which means that you must use double-quotes (") around words not single-quotes (').

Note: Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, RUN [ "echo", "$HOME" ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: RUN [ "sh", "-c", "echo", "$HOME" ].

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 RUNinstructions can be invalidated by using the --no-cache flag, for example docker build --no-cache.

See the Dockerfile Best Practices guide for more information.

The cache for RUN instructions can be invalidated by ADD instructions. See below for details.

Known Issues (RUN)

  • Issue 783 is about file permissions problems that can occur when using the AUFS file system. You might notice it during an attempt to rm a file, for example. The issue describes a workaround.

CMD

The CMD instruction has three forms:

  • CMD ["executable","param1","param2"] (exec form, this is the preferred form)
  • CMD ["param1","param2"] (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 then only the lastCMD will take effect.

The main 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 ENTRYPOINTinstruction as well.

Note: If CMD is used to provide default arguments for the ENTRYPOINT instruction, both the CMD andENTRYPOINT instructions should be specified with the JSON array format.

Note: The exec form is parsed as a JSON array, which means that you must use double-quotes (") around words not single-quotes (').

Note: Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, CMD [ "echo", "$HOME" ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: CMD [ "sh", "-c", "echo", "$HOME" ].

When used in the shell or exec formats, the CMD instruction sets the command to be executed when running the image.

If you use the shell form of the CMD, then the <command> will execute in /bin/sh -c:

FROM ubuntu
CMD echo "This is a test." | wc -

If you want to run your <command> without a shell then you must express the command as a JSON array and give the full path to the executable. This array form is the preferred format of CMD. Any additional parameters must be individually expressed as strings in the array:

FROM ubuntu
CMD ["/usr/bin/wc","--help"]

If you would like your container to run the same executable every time, then you should consider usingENTRYPOINT in combination with CMD. See ENTRYPOINT.

If the user specifies arguments to docker run then they will override the default specified in CMD.

Note: don't confuse RUN with CMDRUN actually runs a command and commits the result; CMD does not execute anything at build time, but specifies the intended command for the image.

EXPOSE

EXPOSE <port> [<port>...]

The EXPOSE instructions informs Docker that the container will listen on the specified network ports at runtime. Docker uses this information to interconnect containers using links (see the Docker User Guide) and to determine which ports to expose to the host when using the -P flag. Note: EXPOSE doesn't define which ports can be exposed to the host or make ports accessible from the host by default. To expose ports to the host, at runtime, use the -p flag or the -P flag.

ENV

ENV <key> <value>
ENV <key>=<value> ...

The ENV instruction sets the environment variable <key> to the value <value>. This value will be in the environment of all "descendent" Dockerfile commands and can be replaced inline in many as well.

The ENV instruction has two forms. The first form, ENV <key> <value>, will set a single variable to a value. The entire string after the first space will be treated as the <value> - including characters such as spaces and quotes.

The second form, ENV <key>=<value> ..., allows for multiple variables to be set at one time. Notice that the second form uses the equals sign (=) in the syntax, while the first form does not. Like command line parsing, quotes and backslashes can be used to include spaces within values.

For example:

ENV myName="John Doe" myDog=Rex\ The\ Dog \
    myCat=fluffy

and

ENV myName John Doe
ENV myDog Rex The Dog
ENV myCat fluffy

will yield the same net results in the final container, but the first form does it all in one layer.

The environment variables set using ENV will persist when a container is run from the resulting image. You can view the values using docker inspect, and change them using docker run --env <key>=<value>.

Note: Environment persistence can cause unexpected effects. For example, setting ENV DEBIAN_FRONTEND noninteractive may confuse apt-get users on a Debian-based image. To set a value for a single command, use RUN <key>=<value> <command>.

ADD

ADD has two forms:

  • ADD <src>... <dest>
  • ADD ["<src>"... "<dest>"] (this form is required for paths containing whitespace)

The ADD instruction copies new files, directories or remote file URLs from <src> and adds them to the filesystem of the container at the path <dest>.

Multiple <src> resource may be specified but if they are files or directories then they must be relative to the source directory that is being built (the context of the build).

Each <src> may contain wildcards and matching will be done using Go's filepath.Match rules. For most command line uses this should act as expected, for example:

ADD hom* /mydir/        # adds all files starting with "hom"
ADD hom?.txt /mydir/    # ? is replaced with any single character

The <dest> is an absolute path, or a path relative to WORKDIR, into which the source will be copied inside the destination container.

ADD test aDir/          # adds "test" to `WORKDIR`/aDir/

All new files and directories are created with a UID and GID of 0.

In the case where <src> is a remote file URL, the destination will have permissions of 600. If the remote file being retrieved has an HTTP Last-Modified header, the timestamp from that header will be used to set themtime on the destination file. Then, like any other file processed during an ADDmtime will be included in the determination of whether or not the file has changed and the cache should be updated.

Note: If you build by passing a Dockerfile through STDIN (docker build - < somefile), there is no build context, so the Dockerfile can only contain a URL based ADDinstruction. You can also pass a compressed archive through STDIN: (docker build - < archive.tar.gz), the Dockerfile at the root of the archive and the rest of the archive will get used at the context of the build.

Note: If your URL files are protected using authentication, you will need to use RUN wgetRUN curl or use another tool from within the container as the ADD instruction does not support authentication.

Note: The first encountered ADD instruction will invalidate the cache for all following instructions from the Dockerfile if the contents of <src> have changed. This includes invalidating the cache for RUNinstructions. See the Dockerfile Best Practices guide for more information.

The copy obeys the following rules:

  • The <src> path must be inside the context of the build; you cannot ADD ../something /something, because the first step of a docker build is to send the context directory (and subdirectories) to the docker daemon.

  • If <src> is a URL and <dest> does not end with a trailing slash, then a file is downloaded from the URL and copied to <dest>.

  • If <src> is a URL and <dest> does end with a trailing slash, then the filename is inferred from the URL and the file is downloaded to <dest>/<filename>. For instance, ADD http://example.com/foobar / would create the file /foobar. The URL must have a nontrivial path so that an appropriate filename can be discovered in this case (http://example.com will not work).

  • If <src> is a directory, the entire contents of the directory are copied, including filesystem metadata.

    Note: The directory itself is not copied, just its contents.

  • If <src> is a local tar archive in a recognized compression format (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources from remote URLs are not decompressed. When a directory is copied or unpacked, it has the same behavior as tar -x: the result is the union of:

    1. Whatever existed at the destination path and
    2. The contents of the source tree, with conflicts resolved in favor of "2." on a file-by-file basis.
  • If <src> is any other kind of file, it is copied individually along with its metadata. In this case, if <dest>ends with a trailing slash /, it will be considered a directory and the contents of <src> will be written at<dest>/base(<src>).

  • If multiple <src> resources are specified, either directly or due to the use of a wildcard, then <dest>must be a directory, and it must end with a slash /.

  • If <dest> does not end with a trailing slash, it will be considered a regular file and the contents of <src>will be written at <dest>.

  • If <dest> doesn't exist, it is created along with all missing directories in its path.

COPY

COPY has two forms:

  • COPY <src>... <dest>
  • COPY ["<src>"... "<dest>"] (this form is required for paths containing whitespace)

The COPY instruction copies new files or directories from <src> and adds them to the filesystem of the container at the path <dest>.

Multiple <src> resource may be specified but they must be relative to the source directory that is being built (the context of the build).

Each <src> may contain wildcards and matching will be done using Go's filepath.Match rules. For most command line uses this should act as expected, for example:

COPY hom* /mydir/        # adds all files starting with "hom"
COPY hom?.txt /mydir/    # ? is replaced with any single character

The <dest> is an absolute path, or a path relative to WORKDIR, into which the source will be copied inside the destination container.

COPY test aDir/          # adds "test" to `WORKDIR`/aDir/

All new files and directories are created with a UID and GID of 0.

Note: If you build using STDIN (docker build - < somefile), there is no build context, so COPY can't be used.

The copy obeys the following rules:

  • The <src> path must be inside the context of the build; you cannot COPY ../something /something, because the first step of a docker build is to send the context directory (and subdirectories) to the docker daemon.

  • If <src> is a directory, the entire contents of the directory are copied, including filesystem metadata.

    Note: The directory itself is not copied, just its contents.

  • If <src> is any other kind of file, it is copied individually along with its metadata. In this case, if <dest>ends with a trailing slash /, it will be considered a directory and the contents of <src> will be written at<dest>/base(<src>).

  • If multiple <src> resources are specified, either directly or due to the use of a wildcard, then <dest>must be a directory, and it must end with a slash /.

  • If <dest> does not end with a trailing slash, it will be considered a regular file and the contents of <src>will be written at <dest>.

  • If <dest> doesn't exist, it is created along with all missing directories in its path.

ENTRYPOINT

ENTRYPOINT has two forms:

  • ENTRYPOINT ["executable", "param1", "param2"] (the preferred exec form)
  • ENTRYPOINT command param1 param2 (shell form)

An ENTRYPOINT allows you to configure a container that will run as an executable.

For example, the following will start nginx with its default content, listening on port 80:

docker run -i -t --rm -p 80:80 nginx

Command line arguments to docker run <image> will be appended after all elements in an exec formENTRYPOINT, and will override all elements specified using CMD. This allows arguments to be passed to the entry point, i.e., docker run <image> -d will pass the -d argument to the entry point. You can override theENTRYPOINT instruction using the docker run --entrypoint flag.

The shell form prevents any CMD or run command line arguments from being used, but has the disadvantage that your ENTRYPOINT will be started as a subcommand of /bin/sh -c, which does not pass signals. This means that the executable will not be the container's PID 1 - and will not receive Unix signals - so your executable will not receive a SIGTERM from docker stop <container>.

Only the last ENTRYPOINT instruction in the Dockerfile will have an effect.

Exec form ENTRYPOINT example

You can use the exec form of ENTRYPOINT to set fairly stable default commands and arguments and then use either form of CMD to set additional defaults that are more likely to be changed.

FROM ubuntu
ENTRYPOINT ["top", "-b"]
CMD ["-c"]

When you run the container, you can see that top is the only process:

$ docker run -it --rm --name test  top -H
top - 08:25:00 up  7:27,  0 users,  load average: 0.00, 0.01, 0.05
Threads:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.1 us,  0.1 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem:   2056668 total,  1616832 used,   439836 free,    99352 buffers
KiB Swap:  1441840 total,        0 used,  1441840 free.  1324440 cached Mem

  PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND
    1 root      20   0   19744   2336   2080 R  0.0  0.1   0:00.04 top

To examine the result further, you can use docker exec:

$ docker exec -it test ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  2.6  0.1  19752  2352 ?        Ss+  08:24   0:00 top -b -H
root         7  0.0  0.1  15572  2164 ?        R+   08:25   0:00 ps aux

And you can gracefully request top to shut down using docker stop test.

The following Dockerfile shows using the ENTRYPOINT to run Apache in the foreground (i.e., as PID 1):

FROM debian:stable
RUN apt-get update && apt-get install -y --force-yes apache2
EXPOSE 80 443
VOLUME ["/var/www", "/var/log/apache2", "/etc/apache2"]
ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

If you need to write a starter script for a single executable, you can ensure that the final executable receives the Unix signals by using exec and gosu commands:

#!/bin/bash
set -e

if [ "$1" = 'postgres' ]; then
    chown -R postgres "$PGDATA"

    if [ -z "$(ls -A "$PGDATA")" ]; then
        gosu postgres initdb
    fi

    exec gosu postgres "$@"
fi

exec "$@"

Lastly, if you need to do some extra cleanup (or communicate with other containers) on shutdown, or are co-ordinating more than one executable, you may need to ensure that the ENTRYPOINT script receives the Unix signals, passes them on, and then does some more work:

#!/bin/sh
# Note: I've written this using sh so it works in the busybox container too

# USE the trap if you need to also do manual cleanup after the service is stopped,
#     or need to start multiple services in the one container
trap "echo TRAPed signal" HUP INT QUIT KILL TERM

# start service in background here
/usr/sbin/apachectl start

echo "[hit enter key to exit] or run 'docker stop <container>'"
read

# stop service and clean up here
echo "stopping apache"
/usr/sbin/apachectl stop

echo "exited $0"

If you run this image with docker run -it --rm -p 80:80 --name test apache, you can then examine the container's processes with docker exec, or docker top, and then ask the script to stop Apache:

$ docker exec -it test ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.1  0.0   4448   692 ?        Ss+  00:42   0:00 /bin/sh /run.sh 123 cmd cmd2
root        19  0.0  0.2  71304  4440 ?        Ss   00:42   0:00 /usr/sbin/apache2 -k start
www-data    20  0.2  0.2 360468  6004 ?        Sl   00:42   0:00 /usr/sbin/apache2 -k start
www-data    21  0.2  0.2 360468  6000 ?        Sl   00:42   0:00 /usr/sbin/apache2 -k start
root        81  0.0  0.1  15572  2140 ?        R+   00:44   0:00 ps aux
$ docker top test
PID                 USER                COMMAND
10035               root                {run.sh} /bin/sh /run.sh 123 cmd cmd2
10054               root                /usr/sbin/apache2 -k start
10055               33                  /usr/sbin/apache2 -k start
10056               33                  /usr/sbin/apache2 -k start
$ /usr/bin/time docker stop test
test
real    0m 0.27s
user    0m 0.03s
sys 0m 0.03s

Note: you can over ride the ENTRYPOINT setting using --entrypoint, but this can only set the binary toexec (no sh -c will be used).

Note: The exec form is parsed as a JSON array, which means that you must use double-quotes (") around words not single-quotes (').

Note: Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, ENTRYPOINT [ "echo", "$HOME" ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: ENTRYPOINT [ "sh", "-c", "echo", "$HOME" ]. Variables that are defined in theDockerfileusing ENV, will be substituted by the Dockerfile parser.

Shell form ENTRYPOINT example

You can specify a plain string for the ENTRYPOINT and it will execute in /bin/sh -c. This form will use shell processing to substitute shell environment variables, and will ignore any CMD or docker run command line arguments. To ensure that docker stop will signal any long running ENTRYPOINT executable correctly, you need to remember to start it with exec:

FROM ubuntu
ENTRYPOINT exec top -b

When you run this image, you'll see the single PID 1 process:

$ docker run -it --rm --name test top
Mem: 1704520K used, 352148K free, 0K shrd, 0K buff, 140368121167873K cached
CPU:   5% usr   0% sys   0% nic  94% idle   0% io   0% irq   0% sirq
Load average: 0.08 0.03 0.05 2/98 6
  PID  PPID USER     STAT   VSZ %VSZ %CPU COMMAND
    1     0 root     R     3164   0%   0% top -b

Which will exit cleanly on docker stop:

$ /usr/bin/time docker stop test
test
real    0m 0.20s
user    0m 0.02s
sys 0m 0.04s

If you forget to add exec to the beginning of your ENTRYPOINT:

FROM ubuntu
ENTRYPOINT top -b
CMD --ignored-param1

You can then run it (giving it a name for the next step):

$ docker run -it --name test top --ignored-param2
Mem: 1704184K used, 352484K free, 0K shrd, 0K buff, 140621524238337K cached
CPU:   9% usr   2% sys   0% nic  88% idle   0% io   0% irq   0% sirq
Load average: 0.01 0.02 0.05 2/101 7
  PID  PPID USER     STAT   VSZ %VSZ %CPU COMMAND
    1     0 root     S     3168   0%   0% /bin/sh -c top -b cmd cmd2
    7     1 root     R     3164   0%   0% top -b

You can see from the output of top that the specified ENTRYPOINT is not PID 1.

If you then run docker stop test, the container will not exit cleanly - the stop command will be forced to send a SIGKILL after the timeout:

$ docker exec -it test ps aux
PID   USER     COMMAND
    1 root     /bin/sh -c top -b cmd cmd2
    7 root     top -b
    8 root     ps aux
$ /usr/bin/time docker stop test
test
real    0m 10.19s
user    0m 0.04s
sys 0m 0.03s

VOLUME

VOLUME ["/data"]

The VOLUME instruction will create a mount point with the specified name and mark it as holding externally mounted volumes from native host or other containers. The value can be a JSON array, VOLUME ["/var/log/"], or a plain string with multiple arguments, such as VOLUME /var/log or VOLUME /var/log /var/db. For more information/examples and mounting instructions via the Docker client, refer to Share Directories via Volumes documentation.

Note: The list is parsed as a JSON array, which means that you must use double-quotes (") around words not single-quotes (').

USER

USER daemon

The USER instruction sets the user name or UID to use when running the image and for any RUNCMD andENTRYPOINT instructions that follow it in the Dockerfile.

WORKDIR

WORKDIR /path/to/workdir

The WORKDIR instruction sets the working directory for any RUNCMDENTRYPOINTCOPY and ADDinstructions that follow it in the Dockerfile.

It can be used multiple times in the one Dockerfile. If a relative path is provided, it will be relative to the path of the previous WORKDIR instruction. For example:

WORKDIR /a
WORKDIR b
WORKDIR c
RUN pwd

The output of the final pwd command in this Dockerfile would be /a/b/c.

The WORKDIR instruction can resolve environment variables previously set using ENV. You can only use environment variables explicitly set in the Dockerfile. For example:

ENV DIRPATH /path
WORKDIR $DIRPATH/$DIRNAME

The output of the final pwd command in this Dockerfile would be /path/$DIRNAME

ONBUILD

ONBUILD [INSTRUCTION]

The ONBUILD instruction adds to the image a trigger instruction to be executed at a later time, when the image is used as the base for another build. The trigger will be executed in the context of the downstream build, as if it had been inserted immediately after the FROM instruction in the downstream Dockerfile.

Any build instruction can be registered as a trigger.

This is useful if you are building an image which will be used as a base to build other images, for example an application build environment or a daemon which may be customized with user-specific configuration.

For example, if your image is a reusable Python application builder, it will require application source code to be added in a particular directory, and it might require a build script to be called after that. You can't just callADD and RUN now, because you don't yet have access to the application source code, and it will be different for each application build. You could simply provide application developers with a boilerplateDockerfile to copy-paste into their application, but that is inefficient, error-prone and difficult to update because it mixes with application-specific code.

The solution is to use ONBUILD to register advance instructions to run later, during the next build stage.

Here's how it works:

  1. When it encounters an ONBUILD instruction, the builder adds a trigger to the metadata of the image being built. The instruction does not otherwise affect the current build.
  2. At the end of the build, a list of all triggers is stored in the image manifest, under the key OnBuild. They can be inspected with the docker inspect command.
  3. Later the image may be used as a base for a new build, using the FROM instruction. As part of processing the FROM instruction, the downstream builder looks for ONBUILD triggers, and executes them in the same order they were registered. If any of the triggers fail, the FROM instruction is aborted which in turn causes the build to fail. If all triggers succeed, the FROM instruction completes and the build continues as usual.
  4. Triggers are cleared from the final image after being executed. In other words they are not inherited by "grand-children" builds.

For example you might add something like this:

[...]
ONBUILD ADD . /app/src
ONBUILD RUN /usr/local/bin/python-build --dir /app/src
[...]

Warning: Chaining ONBUILD instructions using ONBUILD ONBUILD isn't allowed.

Warning: The ONBUILD instruction may not trigger FROM or MAINTAINER instructions.

Dockerfile Examples

# Nginx
#
# VERSION               0.0.1

FROM      ubuntu
MAINTAINER Victor Vieux <victor@docker.com>

RUN apt-get update && apt-get install -y inotify-tools nginx apache2 openssh-server

# Firefox over VNC
#
# VERSION               0.3

FROM ubuntu

# Install vnc, xvfb in order to create a 'fake' display and firefox
RUN apt-get update && apt-get install -y x11vnc xvfb firefox
RUN mkdir ~/.vnc
# Setup a password
RUN x11vnc -storepasswd 1234 ~/.vnc/passwd
# Autostart firefox (might not be the best way, but it does the trick)
RUN bash -c 'echo "firefox" >> /.bashrc'

EXPOSE 5900
CMD    ["x11vnc", "-forever", "-usepw", "-create"]

# Multiple images example
#
# VERSION               0.1

FROM ubuntu
RUN echo foo > bar
# Will output something like ===> 907ad6c2736f

FROM ubuntu
RUN echo moo > oink
# Will output something like ===> 695d7793cbe4

# You᾿ll now have two images, 907ad6c2736f with /bar, and 695d7793cbe4 with
# /oink.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

docker 最新Dockerfile命令手册 的相关文章

  • pyecharts——WordCloud词云图

    转自 xff1a pyecharts学习笔记 WordCloud词云图 码农家园 基本 词云图 注意数据格式 xff0c word1 count1 word2 count2 xff0c 可使用 counter 做词频统计 xff0c 生成这
  • 一个中文词云项目的使用总结

    一个中文词云项目的使用总结 用一个pa wordcloud项目来生成词云图的时候碰到了好几个问题 xff0c 一个pillow库安装问题 xff0c 卸载重新安装了最新版本 xff0c 就是numpy版本不匹配问题 xff0c 安装了对应p
  • 圆周率怎么计算来的?教你利用欧拉恒等式,生成圆周率万能公式!

    原文链接 xff1a http www twoeggz com news 4791962 html 在古代 xff0c 缺少数学技巧的情况下 xff0c 圆周率的计算是相当困难的 xff0c 我们国家伟大的数学家 xff0c 天文学家祖冲之
  • 影片avi转rmvb教程

    昨天被迫压制 MS IGLOO 正好学习了下影片avi转rmvb的技术 找来找去发现篇文章似乎不错 现在根据自己的操作过程 xff0c 加点操作心得再内 xff0c 保留一篇备用 xff01 首先还是要有专门压制的的软件 xff0c 之前我
  • 手机摄像头的等效焦距

    笔者随意拿出一张最近评测文章中的样张 xff0c EXIF信息就位于照片的下方 我们看到 xff0c 光圈 ISO感光度 曝光时间 曝光补偿这样的参数都比较好理解 xff0c 唯独这个焦距确实让不少人生疑 焦距 4mm 光圈 f 2 4 I
  • 关于3D打印文件格式:STL、OBJ、AMF、3MF的详解

    很多人对3D打印的数据格式颇有微词 xff0c 辛辛苦苦用三维软件设计好的作品 xff0c 一转换成3D打印格式 xff0c 基本就从白天鹅变成丑小鸭了 xff0c 既没有颜色 xff0c 数据也不完整 xff0c 形状重叠表面破损那是常有
  • 在线绘制函数图像和在线图标绘制网址

    经过寻找 xff0c 找到了几个在线绘制函数图像的网址 xff0c 可以不用matlab和geogebra软件绘制了 数学函数图像 xff1a 第一个 xff1a Desmos 首推 第二个 xff1a fooplot 可以绘制分段函数比如
  • geogebra中函数的定义域的输入

    ggb中函数的输入有如下几种方式 xff1a 一 如果if做法 1 区间函数 xff1a 做出函数在某区间上的图象 xff1a f x 61 if x gt 61 0 amp amp x lt 61 2 x 2 43 2x 1 2 分段函数
  • 升级Ubuntu内核

    自己下载deb或使用某些其他工具 xff0c 无脑dpkg deb会导致Depends libc6 gt 61 2 33 but 2 31 ubuntu9 2 is to be installed的错误 xff08 猜测该错误产生的原因是没
  • 在ROS的noetic版本中通过rosrun运行python文件

    xff08 1 xff09 不要将python文件放入scr目录中 xff0c 否则后续编译工作空间会报如图所示的错误 首先要在功能包文件夹 xff08 catkin ws src learnning topic xff09 中创建一个sc
  • linux音量调节

    转自 xff1a https www jianshu com p fc8c8cad67d6 一 alsa设置默认声卡 alsa设置默认声卡 理解和使用Alsa的配置文件 alsa的配置文件是alsa conf位于 usr share als
  • FutureTask实际应用案例

    GetResultTask java package com cwp data service service task import com cwp data intelligence common exception RRExcepti
  • 异常检测算法综述

    一 异常检测 随着人工智能的火热 xff0c 运维人员也开始考虑将算法引入运维领域 xff0c 对传统DevOps的核心功能进行优化改进 异常检测是运维不可或缺的重要要功能模块之一 xff0c 可以提升企业运维能力和效率 xff0c 释放运
  • 每日一书丨嵌入式C语言自我修养:从芯片、编译器到操作系统

    最近 xff0c 阅读了王工 xff08 王利涛 xff09 赠送的一本由他编著的书籍 嵌入式C语言自我修养 xff0c 感觉写的挺不错 今天分享一下这本书籍 嵌入式C语言自我修养 xff1a 从芯片 编译器到操作系统 从芯片 编译器到操作
  • JSP提交仍然停留在当前页面

    在C S结构中 xff0c 用户提交内容以后 xff0c 系统任停留在当前页面上 xff0c 直到服务返回处理成功或者失败的提示 而用户录入的信息 xff0c 除非程序清除 xff0c 否则不会自动消失 xff0c 方便用户修改 为了解决这
  • FreeRTOS Queue

    变量定义 span class token keyword typedef span span class token keyword void span span class token operator span QueueHandle
  • 专门讲解无人机航拍图像处理的书【包括图像拼接!!!】

    最近正式开始做课设啦 xff0c 博主在网上搜集到有专门的书讲解无人机航拍图像的处理 xff0c 包括图像拼接 xff01 xff01 xff01 更非常激动的是博主在图书馆把两本书都找到了 xff0c 俺滴学校i了i了 两本书如下所示 x
  • 1.2 向量与线性代数

    向量与线性代数 图形学基础向量向量点乘向量叉乘矩阵 图形学基础 基础数学 xff1a 线性代数 统计学 微积分基础物理 xff1a 其他课程 xff1a 信号处理 数学分析一点点 xff1a 美学课程 向量 方向长度单位向量向量加法 向量点
  • 2.1 变换

    矩阵变换 二维变换齐次坐标齐次坐标下的二维变换矩阵逆变换 xff08 逆矩阵 xff09 复合变换三维空间仿射变换 modeling and viewing 模型变换和视角变换 二维变换 尺度变换 Scale 镜像变换 切变变换 旋转变换
  • 2.2 变换(模型、视图、投影)

    变换 xff08 模型 视图 投影 xff09 三维变换观测变换 xff08 Viewing transformation xff09 视图 xff08 View xff09 定义相机如何将相机移动到约定俗成位置 投影 xff08 Proj

随机推荐

  • 四轴飞行器入门——基础知识

    引言 从2016年起 xff0c 细细数来入门无人机已经有两年时间 两年期间 xff0c 自己边学边摸索 xff0c 组装过机架四轴无人机 xff0c 也修改过开源飞控的代码 xff0c 但是因为种种原因 xff0c 始终没有写过相关博客记
  • Linux系统下搭建PX4/Pixhawk原生固件编译环境

    简介 PX4固件是Pixhawk飞行控制器的官方固件 xff0c Pixhawk官网也给出了Linux windows下搭建开发环境的方法 由于种种原因 xff0c 搭建开发环境时总会遇到各种各样的bug xff0c 致使PX4固件编译失败
  • main(int argc, char *argv[])

    这是UNIX和Linux中的标准主函数 argc 用来统计运行时发送给main函数的命令行参数的个数 argv 其中每个元素都是上述参数 以字符串形式存储 的首地址 argv 0 指向程序运行的全路径名 argv 1 指向程序名后的第一个参
  • 为PX4添加串口通讯模块(模块结构)

    主要讲模块的结构 不贴代码 从最外层开始 执行read uart main start dev ttyS1 read uart main int argc char argv 入口函数 判断任务进程read uart task是否存在 根据
  • C++抽象基类与虚基类(C++ primer)

    c 43 43 primer plus P508 xff0c 抽象基类 c 43 43 primer plus P556 xff0c 虚基类 抽象基类 xff08 abstract base class xff0c ABC xff09 抽象
  • MFC学习笔记(二)处理命令行选项

    目标 让应用程序处理这里所见的命令行标志 gt XXX exe c d 策略 一个MFC应用程序可以用CCommandLineInfo类的成员函数ParseParam 处理一些标准标 志 要添加我们自己的标志 xff0c 而仍然能够支持另外
  • C++ expection异常类、捕获所有异常(C++ primer,P639)

    expection类 头文件 lt expection gt stdexcept类 C 43 43 primer plus xff0c P632 包含以下异常 xff1a domain errorinvalid argumentlength
  • 5.1 运输层协议

    运输层协议 运输层的复用与常见端口常用端口 UDP协议特点UDP帧格式 TCP协议特点socket套接字可靠传输工作原理TCP帧首部重要字段 TCP可靠传输以字节为单位的滑动窗口选择超时重传时间选择确认SACK xff08 未经常使用P22
  • Linux上VScode + cmake + gcc开发环境搭建

    VScode 43 cmake 43 gcc 下载 安装vscode安装插件cmake文件结构vscode修改json文件编译 调试的过程 下载 安装 span class token comment cmake gcc 安装都很简单 sp
  • 软件测试面试04:实战项目介绍

    4 1 简单介绍下最近做过的项目 根据自己的项目整理完成 xff0c 要点 xff1a 1 xff09 项目背景 业务 需求 核心业务的流程 2 xff09 项目架构 xff0c B S还是C 5 xff0c 数据库用的什么 中间件用的什么
  • 一张图搞定SDF的概念

    本文仅代表个人理解 xff0c 谬误之处请指正 SDF Signed Distance Field 译为有向距离场 xff0c 有向 距离 场 这三个词非常精确的描述了 sdf 究竟是个什么东西 GPU Gems 3 中是这么描述 sdf
  • Ubuntu Windows双系统切换最简方法!!!

    安装完Ubuntu windows双系统后的第一个问题 xff1a 该怎么在两个系统间快速自由切换呢 xff1f 本文给出两种无需命令行的实用易上手方式 一 什么 xff0c 你要快快快快速切换 xff1f 这里直接给出答案 xff0c F
  • C++primer(第五版)习题答案

    前两章习题较简单 xff0c 这里就不作整理了 xff0c 直接从第三章开始 持续更新 xff1a Chapter 3 Strings Vectors and Arrays Exercise 3 1 part 1 include lt io
  • PX4源码地址和wiki

    源码 https github com 987419640 Firmware wiki https dev px4 io v1 9 0 zh concept architecture html
  • 视觉十四讲:第七讲_2D-2D:对极几何估计姿态

    1 对极几何 从2张图片中 得到若干个配对好的2d特征点 就可以运用对极几何来恢复出两帧之间的运动 设P的空间坐标为 P 61 X Y Z T 两个像素点 p 1 p 2 的像素坐标为 s 1 p 1 61 KP s 2 p 2 61 K
  • VINS_FUSION入门系列---GPS与VIO融合

    参考的博客 https blog csdn net subiluo article details 105429471 http www luyixian cn news show 313718 aspx state 状态量 位姿 速度 b
  • 几种常用加壳软件图文详解

    为了保护自己的软件不轻易被他人 借鉴 xff0c 有必要对软件进行一些加密保护 xff0c 而这方面目前己有成熟的专业加密软件可选择 但不要太依赖壳的保护 xff0c 大多数壳是可以被攻破的 xff0c 还是在自身保护上下些功夫 加密软件比
  • debian添加source源后update出现GPG错误

    错误如下 xff1a W GPG error http mirrors 163 com debian buster updates InRelease The following signatures couldn 39 t be veri
  • windows clang 编译Qt

    准备 xff1a qt everywhere src 5 15 0 zip jom 1 1 3 zip LLVM 10 0 0 win64 exe VS2019 xff1a 需要安装win10 SDK xff0c 也有自带的clang xf
  • docker 最新Dockerfile命令手册

    Dockerfile Reference Docker can build images automatically by reading the instructions from a Dockerfile A Dockerfile is