This article brings you relevant knowledge about the dockerFile command. This command contains instructions one by one. Each instruction builds a layer of image production files. I hope it will be helpful to everyone.

Recommended study: "docker video tutorial"
DockerFile command detailed explanation
Dockerfile contains instructions one by one , each instruction builds a layer of image production files.
Build the image
docker build [选项] docker build -t nginx:v3 . # . 表示Dockerfile在当前目录
FROM specifies the base image
Specify the base image through FROM, so FROM is required in a Dockerfile command for the device and must be the first command.
FROM scratch, this image is a virtual concept and does not actually exist. It represents a blank image. The following instructions will begin to exist as the first layer of the image.
RUN execution command
RUN is used to execute command line commands. There are two formats:
shell format:
RUN RUN echo '<h1 id="Hello-Docker">Hello, Docker!</h1>' > /usr/share/nginx/html/index.html
exec format:
RUN ["可执行文件", "参数1", "参数2"]
Union FS has a limit on the maximum number of layers. For example, AUFS used to have a maximum limit of 42 layers, but now it cannot exceed 127 layers. For the same function, && should be used to concatenate the required commands. Simplify the number of image layers
COPY Copy files
COPY [--chown=<user>:<group>] COPY [--chown=<user>:<group>] ["",... ""]</group></user></group></user>
# 把当前目录的a.txt文件复制到镜像的根目录 COPY a.txt /a.txt
ADD Copy files (download files or unzip files)
ADD [--chown=<user>:<group>] http://xxx # 下载文件到镜像的目标路径 ADD [--chown=<user>:<group>] ./a.tar.gz # 复制压缩包,并自动解压到目标路径</group></user></group></user>
CMD specifies the default startup command of the container main process
CMD ["可执行文件", "参数1", "参数2"...]
# 指定进入容器马上指定 cat /a.txt CMD ["sh","-c", "cat /a.txt"]
When executing the docker run -it image, if you do not specify a command similar to /bin/bash, sh -c cat will be automatically executed /a.txt, otherwise the startup command of the container main process will be specified according to the user-specified CMD
ENTRYPOINT, similar to CMD
The format is consistent with CMD, the difference is
1. Use ENTRYPOINT to pass parameters
Specify ENTRYPOINT [ "curl", "-s", "http://myip.ipip.net" ] in the Dockerfile, and the command line is through docker run When myip -i, the -i parameter will be passed to the ENTRYPOINT command. When finally entering the
container, the container will execute curl -s http://myip.ipip.net -i
2. Execute Some initialization work that has nothing to do with CMD and has nothing to do with container CMD, no matter what the CMD is, a preprocessing work needs to be done in advance.
Similar to ENTRYPOINT ["docker-entrypoint.sh"] This script checks whether the user's identity is legal, etc.
ENV sets environment variables
ENV <key> <value> ENV <key1>=<value1> <key2>=<value2>...</value2></key2></value1></key1></value></key>
ARG build parameters
ARG [=]
The ARG instruction has a valid range. If specified before the FROM instruction, it can only be used in the FROM instruction.
ARG DOCKER_USERNAME=library
FROM ${DOCKER_USERNAME}/alpine
If specified after FROM, the variables used in each stage must be specified in each stage separately
FROM ${DOCKER_USERNAME}/alpine
# 在FROM 之后使用变量,必须在每个阶段分别指定
ARG DOCKER_USERNAME=library
RUN set -x ; echo ${DOCKER_USERNAME}
VOLUME anonymous volume
VOLUME ["", ""...] VOLUME
In order to prevent users from forgetting to mount the directory where dynamic files are saved as volumes during runtime, in the Dockerfile, certain directories can be specified in advance to be mounted as anonymous volumes, so that if the user does not specify mounting at runtime, the application can also During normal operation, a large amount of data will not be written to the container storage layer.
The /data directory here will be automatically mounted as an anonymous volume when the container is running, and any information written to /data will not be recorded. into the container storage layer, thus ensuring the statelessness of the container storage layer.
EXPOSE Expose port
EXPOSE [...]
The EXPOSE instruction declares the port that the container provides services when it is running. EXPOSE only declares what port the container intends to use, and will not automatically The host performs port mapping.
Writing such a statement in the Dockerfile has two benefits. One is to help image users understand the guard port of this image service to facilitate configuration mapping;
The other is to When using random port mapping at runtime, that is, when docker run -P is used, the EXPOSE port will be automatically and randomly mapped.
To distinguish EXPOSE from using -p
-p is to map the host port and the container port. In other words, it exposes the corresponding port service of the container to the outside world.
WORKDIR specifies the working directory. If the directory does not exist, WORKDIR will create the directory
WORKDIR
Example 1:
WORKDIR /app RUN echo "hello" > world.txt
Example 2:
WORKDIR /a WORKDIR b WORKDIR c RUN pwd ## RUN pwd 的工作目录为 /a/b/c
USER Specify the current user
USER [:]
If you want to change the identity of a script executed as root during execution, for example, you want to run a service as an already established user Process, do not use su or sudo, these require more troublesome configuration, and often errors occur in environments where TTY is missing. It is recommended to use gosu.
# 建立 redis 用户,并使用 gosu 换另一个用户执行命令 RUN groupadd -r redis && useradd -r -g redis redis # 下载 gosu RUN wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/1.12/gosu-amd64" \ && chmod +x /usr/local/bin/gosu \ && gosu nobody true # 设置 CMD,并切换到redis用户执行 CMD [ "exec", "gosu", "redis", "redis-server" ]
HEALTHCHECK tells Docker how to determine whether the status of the container is normal
HEALTHCHECK [选项] CMD :设置检查容器健康状况的命令 HEALTHCHECK NONE:如果基础镜像有健康检查指令,使用这行可以屏蔽掉其健康检查指令
Options:
--interval=:两次健康检查的间隔,默认为 30 秒; --timeout=:健康检查命令运行超时时间,如果超过这个时间,本次健康检查就被视为失败,默认 30 秒; --retries=:当连续失败指定次数后,则将容器状态视为 unhealthy,默认 3 次
When the HEALTHCHECK instruction is specified in an image, Use it to start the container. The initial state will be starting. After the HEALTHCHECK instruction is successfully checked, it will become healthy. If it fails a certain number of times in a row, it will become unhealthy.
HEALTHCHECK can only appear once. If multiple are written, only the last one will take effect
CMD 命令的返回值决定了该次健康检查的成功与否:0:成功;1:失败
ONBUILD 指定某些命令只有当以当前镜像为基础镜像,去构建下一级镜像的时候才会被执行
ONBUILD
# 举例如下Dockerfile,初次构建为镜像my-node时,ONBUILD的三行命令不会执行 FROM node:slim RUN mkdir /app WORKDIR /app ONBUILD COPY ./package.json /app ONBUILD RUN [ "npm", "install" ] ONBUILD COPY . /app/ CMD [ "npm", "start" ] # 只要当其他镜像 FROM my-node 从上面镜像作为基础镜像进行构建时,ONBUILD 的命令开始执行
LABEL 为镜像添加元数据
LABEL <key>=<value> <key>=<value> <key>=<value> ...</value></key></value></key></value></key>
# 标注镜像的作者 LABEL org.opencontainers.image.authors="yeasy"
SHELL 指定执行shell命令的参数
SHELL ["可执行程序", "参数"]
SHELL ["/bin/sh", "-c"] RUN lll ; ls # 这里的shell命令将通过 /bin/sh -c 的方式执行
推荐学习:《docker视频教程》
The above is the detailed content of Take you to understand the DockerFile command in depth. For more information, please follow other related articles on the PHP Chinese website!
Linux and Docker: Docker on Different Linux DistributionsApr 19, 2025 am 12:10 AMThe methods of installing and using Docker on Ubuntu, CentOS, and Debian are different. 1) Ubuntu: Use the apt package manager, the command is sudoapt-getupdate&&sudoapt-getinstalldocker.io. 2) CentOS: Use the yum package manager and you need to add the Docker repository. The command is sudoyumininstall-yyum-utils&&sudoyum-config-manager--add-repohttps://download.docker.com/lin
Mastering Docker: A Guide for Linux UsersApr 18, 2025 am 12:08 AMUsing Docker on Linux can improve development efficiency and simplify application deployment. 1) Pull Ubuntu image: dockerpullubuntu. 2) Run Ubuntu container: dockerrun-itubuntu/bin/bash. 3) Create Dockerfile containing nginx: FROMubuntu;RUNapt-getupdate&&apt-getinstall-ynginx;EXPOSE80. 4) Build the image: dockerbuild-tmy-nginx. 5) Run container: dockerrun-d-p8080:80
Docker on Linux: Applications and Use CasesApr 17, 2025 am 12:10 AMDocker simplifies application deployment and management on Linux. 1) Docker is a containerized platform that packages applications and their dependencies into lightweight and portable containers. 2) On Linux, Docker uses cgroups and namespaces to implement container isolation and resource management. 3) Basic usages include pulling images and running containers. Advanced usages such as DockerCompose can define multi-container applications. 4) Debug commonly used dockerlogs and dockerexec commands. 5) Performance optimization can reduce the image size through multi-stage construction, and keeping the Dockerfile simple is the best practice.
Docker: Containerizing Applications for Portability and ScalabilityApr 16, 2025 am 12:09 AMDocker is a Linux container technology-based tool used to package, distribute and run applications to improve application portability and scalability. 1) Dockerbuild and dockerrun commands can be used to build and run Docker containers. 2) DockerCompose is used to define and run multi-container Docker applications to simplify microservice management. 3) Using multi-stage construction can optimize the image size and improve the application startup speed. 4) Viewing container logs is an effective way to debug container problems.
How to start containers by dockerApr 15, 2025 pm 12:27 PMDocker container startup steps: Pull the container image: Run "docker pull [mirror name]". Create a container: Use "docker create [options] [mirror name] [commands and parameters]". Start the container: Execute "docker start [Container name or ID]". Check container status: Verify that the container is running with "docker ps".
How to view logs from dockerApr 15, 2025 pm 12:24 PMThe methods to view Docker logs include: using the docker logs command, for example: docker logs CONTAINER_NAME Use the docker exec command to run /bin/sh and view the log file, for example: docker exec -it CONTAINER_NAME /bin/sh ; cat /var/log/CONTAINER_NAME.log Use the docker-compose logs command of Docker Compose, for example: docker-compose -f docker-com
How to check the name of the docker containerApr 15, 2025 pm 12:21 PMYou can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).
How to create containers for dockerApr 15, 2025 pm 12:18 PMCreate a container in Docker: 1. Pull the image: docker pull [mirror name] 2. Create a container: docker run [Options] [mirror name] [Command] 3. Start the container: docker start [Container name]


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment







