Dockerfile Commands#
ARG#
- Use build-time variables.
- The
ARGinstruction defines a variable that users can pass at build-time to the builder with thedocker buildcommand using the--build-arg <varname>=<value>flag. ARGvariables are not persisted into the built image- An
ARGvariable comes into effect from the line on which it is declared in the Dockerfile.
Predefined ARG variables that you can use without a corresponding ARG instruction in the Dockerfile:
HTTP_PROXYhttp_proxyHTTPS_PROXYhttps_proxyFTP_PROXYftp_proxyNO_PROXYno_proxyALL_PROXYall_proxy
BuildKit also provides some global and inbuild arguments, refer: https://docs.docker.com/reference/dockerfile/#automatic-platform-args-in-the-global-scope
ENV#
- Set environment variable
- The
ENVinstruction sets the environment variable<key>to the value<value>. - Unlike an
ARGinstruction,ENVvalues are always persisted in the built image. - The environment variables set using
ENVwill persist when a container is run from the resulting image.
#ENV Key Value
ENV NAME World
FROM#
- Create a new build stage from a base image.
- The FROM instruction initializes a new build stage and sets the base image for subsequent instructions.
- Specifies the base image to build upon.
FROM [--platform=<platform>] <image> [AS <name>]
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]
FROM [--platform=<platform>] <image>[@<digest>] [AS <name>]
HEALTHCHECK#
- Check a container’s health on startup.
- The
HEALTHCHECKinstruction tells Docker how to test a container to check that it’s still working. - Example for health check: A web server stuck in an infinite loop and unable to handle new connections should show unhealthy.
- There can only be one
HEALTHCHECKinstruction in a Dockerfile. - The
HEALTHCHECKinstruction has two forms:HEALTHCHECK [OPTIONS] CMD command(check container health by running a command inside the container)HEALTHCHECK NONE(disable any healthcheck inherited from the base image)
#check every five minutes or so that a web-server is able to serve the site's main page within three seconds
HEALTHCHECK --interval=5m --timeout=3s CMD curl -f http://localhost/ || exit 1
LABEL#
- Add metadata to an image.
- The
LABELinstruction adds metadata to an image. - A
LABELis a key-value pair.
LABEL <key>=<value> [<key>=<value>...]
ONBUILD#
- Specify instructions for when the image is used in a build.
- The
ONBUILDinstruction 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
FROMinstruction in the downstream Dockerfile. - Use case: An application build environment or a daemon which may be customized with user-specific configuration.
ONBUILD <INSTRUCTION>
WORKDIR#
- Change working directory.
- The
WORKDIRinstruction sets the working directory for anyRUN,CMD,ENTRYPOINT,COPYandADDinstructions that follow it in the Dockerfile. - If the
WORKDIRdoesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction. - Sets the working directory inside the container.
WORKDIR /path/to/workdir
Example of WORKDIR
WORKDIR /a
WORKDIR b
WORKDIR c
RUN pwd
#will result in a/b/c
COPY#
- Copy files and directories.
- The
COPYinstruction copies new files or directories from<src>and adds them to the filesystem of the image at the path<dest>. - All files and directories copied from the build context are created with a UID and GID of
0
COPY [OPTIONS] <src> ... <dest>
COPY [OPTIONS] ["<src>", ... "<dest>"]
- The
COPY --fromflag lets you copy files from an image, a build stage, or a named context instead. - The
--chownand--chmodfeatures are only supported on Dockerfiles used to build Linux containers. - Use
--linkto reuse already built layers in subsequent builds with--cache-fromeven if the previous layers have changed. - The
--excludeflag lets you specify a path expression for files to be excluded.
ADD#
- Add local or remote files and directories.
- The
ADDinstruction copies new files or directories from<src>and adds them to the filesystem of the image at the path<dest>. - Files and directories can be copied from the build context, a remote URL, or a Git repository.
- If the source is a directory, the contents of the directory are copied, including filesystem metadata. The directory itself isn’t copied, only its contents.
- If it contains subdirectories, these are also copied and merged with any existing directories at the destination.
- If the destination path begins with a forward slash, it’s interpreted as an absolute path
ADD [OPTIONS] <src> ... <dest>
ADD [OPTIONS] ["<src>", ... "<dest>"]
--checksumflag lets you verify the checksum of a remote resource.- The
--chownand--chmodfeatures are only supported on Dockerfiles used to build Linux containers.--chown=myuser:mygroup --chmod=644 files* /somedir/ --linkfiles remain independent on their own layer and don’t get invalidated when commands on previous layers are changed.--excludeflag lets you specify a path expression for files to be excluded.
COPYsupports basic copying of files into the container, from the build context or from a stage in a multi-stage build.ADDsupports features for fetching files from remote HTTPS and Git URLs, and extracting tar files automatically when adding files from the build context.
RUN#
- Execute build commands.
- The
RUNinstruction will execute any commands to create a new layer on top of the current image. - The cache for
RUNinstructions isn’t invalidated automatically during the next build. - The cache for
RUNinstructions can be invalidated by using the--no-cacheflag, for exampledocker build --no-cache- The cache for
RUNinstructions can be invalidated byADDandCOPYinstructions.
- The cache for
# Shell form:
RUN [OPTIONS] <command> ...
# Exec form:
RUN [OPTIONS] [ "<command>", ... ]
RUN --mountallows you to create filesystem mounts that the build can access. This can be used to:- Create a 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
- Different mount type:
bindThis mount type allows binding files or directories to the build container. A bind mount is read-only by default.cacheThis mount type allows the build container to cache directories for compilers and package managers.tmpfsThis mount type allows mountingtmpfsin the build containersecretThis mount type allows the build container to access secret values, such as tokens or private keys, without baking them into the image.sshThis mount type allows the build container to access SSH keys via SSH agents, with support for passphrases.- Refer to other optional parameters https://docs.docker.com/reference/dockerfile/#run---mount
RUN --networkallows control over which networking environment the command is run in.- The supported network types are:
defaultEquivalent to not supplying a flag at all, the command is run in the default network for the build.noneThe command is run with no network access (lois still available, but is isolated to this process)hostThe command is run in the host’s network environment (similar todocker build --network=host, but on a per-instruction basis)
SHELL#
- Set the default shell of an image.
- The
SHELLinstruction allows the default shell used for the shell form of commands to be overridden.
SHELL ["executable", "parameters"]
STOPSIGNAL#
- Specify the system call signal for exiting a container.
- The
STOPSIGNALinstruction sets the system call signal that will be sent to the container to exit.
STOPSIGNAL signal
USER#
- Set user and group ID.
- The
USERinstruction sets the user name (or UID) and optionally the user group (or GID) to use as the default user and group for the remainder of the current stage. - The specified user is used for
RUNinstructions and at runtime, runs the relevantENTRYPOINTandCMDcommands. - When the user doesn’t have a primary group then the image (or the next instructions) will be run with the
rootgroup.
USER <user>[:<group>]
USER <UID>[:<GID>]
VOLUME#
- Create volume mounts.
- Volumes are persistent data stores for containers, created and managed by Docker.
- The
VOLUMEinstruction creates a mount point with the specified name and marks it as holding externally mounted volumes from native host or other containers. - They retain data even after the containers using them are removed.
- This is similar to the way that bind mounts work, except that volumes are managed by Docker and are isolated from the core functionality of the host machine.
- Volumes are the preferred mechanism for persisting data generated by and used by Docker containers.
VOLUME ["/data"]
CMD#
- Specify default commands.
- The CMD instruction sets the command to be executed when running a container from an image.
- There can only be one
CMDinstruction in a Dockerfile. - The purpose of a
CMDis 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 anENTRYPOINTinstruction as well. - If the user specifies arguments to
docker runthen they will override the default specified inCMD, but still use the defaultENTRYPOINT.
#exec form
CMD ["executable","param1","param2"]
#exec form with default parameters to ENTRYPOINT
CMD ["param1","param2"]
#shell form; avoid this
CMD command param1 param2
ENTRYPOINT#
- Specify default executable.
- An ENTRYPOINT allows you to configure a container that will run as an executable
- ENTRYPOINT should be used when you want to define a container’s main application or command, ensuring it always runs regardless of additional CMD parameters
ENTRYPOINTshould be defined when using the container as an executable.CMDshould be used as a way of defining default arguments for anENTRYPOINTcommand or for executing an ad-hoc command in a container.
#exec form
ENTRYPOINT ["executable", "param1", "param2"]
#shell form
ENTRYPOINT command param1 param2
- Dockerfile should specify at least one of
CMDorENTRYPOINTcommands. -ENTRYPOINTshould be defined when using the container as an executable.
EXPOSE#
- Describe which ports your application is listening on.
- The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime.
- When creating a container image, the
EXPOSEInstruction is used to indicate that the packaged application will use the specified port. - These ports aren’t published by default.
- It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published.
- The following flags can be used with
docker run- With the
-Por--publish-allflag, you can automatically publish all exposed ports to ephemeral ports. -por--exposePublish port.-Por--publish-allPublish all exposed ports.
- With the
- Without
EXPOSEcommand in Dockerfile and runningdocker runwithout specifying-p HOST_PORT:CONTAINER_PORT- The Docker container is not accessible. The
docker container ps -adoes not show any port mapping.
- The Docker container is not accessible. The
- With
EXPOSEcommand in Dockerfile and runningdocker runwithout specifying-p HOST_PORT:CONTAINER_PORT- The Docker container is not accessible. The
docker container ps -ashows the port specified onEXPOSEIt should be accessible internally.
- The Docker container is not accessible. The
- Without
EXPOSEcommand in Dockerfile and runningdocker runwith specifying-p HOST_PORT:CONTAINER_PORT- The Docker container is accessible on the host port
HOST_PORT - Specifying
-p portDocker assigns a randomly generated host port. The mapping israndom host post -> portfound in thedocker container ps -a. The-p portshould be the port the underlying service is listening on. The Docker container is accessible. - Specifying
-Pthedocker container ps -adoes not specify any port sinceEXPOSEcommand is not used in the Dockerfile. The Docker container is not accessible.
- The Docker container is accessible on the host port
- With
EXPOSEcommand in Dockerfile and runningdocker runwith specifying-p HOST_PORT:CONTAINER_PORT- Specifying the same port on
EXPOSE HOST_PORTand a host port indocker run -p HOST_PORT:CONTAINER_PORT. The container is accessible on the host portHOST_PORT - Specifying a different port on
EXPOSE **SOME_PORT**and a host port indocker run -p HOST_PORT:CONTAINER_PORT. The container is accessible on the host portHOST_PORT - Specifying
-Pthe docker service is accessible on a random port which can be gotten fromdocker container ps -a
- Specifying the same port on
When mapping with
-p HOST_PORT:CONTAINER_PORTit is important to note that the underlying service is running on theCONTAINER_PORT. If the underlying service is listening on port90but thedocker runcommand specifies-p 8080:80you cannot access the service the mapping should be-p 8080:90.
EXPOSE <port> [<port>/<protocol>...]
