Table of Contents
DockerFile command detailed explanation
Home Operation and Maintenance Docker Take you to understand the DockerFile command in depth

Take you to understand the DockerFile command in depth

Feb 22, 2022 pm 05:40 PM
docker

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.

Take you to understand the DockerFile command in depth

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 [选项] <上下文路径/URL/->

docker build -t nginx:v3 .           # . 表示Dockerfile在当前目录
Copy after login

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>Hello, Docker!</h1>' > /usr/share/nginx/html/index.html
Copy after login

exec format:

RUN ["可执行文件", "参数1", "参数2"]
Copy after login

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>] ["<宿主机源路径1>",... "<镜像内的目标路径>"]
Copy after login
# 把当前目录的a.txt文件复制到镜像的根目录
COPY a.txt /a.txt
Copy after login

ADD Copy files (download files or unzip files)

ADD [--chown=<user>:<group>] http://xxx <目标路径>       # 下载文件到镜像的目标路径
ADD [--chown=<user>:<group>] ./a.tar.gz <目标路径>       # 复制压缩包,并自动解压到目标路径
Copy after login

CMD specifies the default startup command of the container main process

CMD ["可执行文件", "参数1", "参数2"...]
Copy after login
# 指定进入容器马上指定 cat /a.txt

CMD ["sh","-c", "cat /a.txt"]
Copy after login

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>...
Copy after login

ARG build parameters

ARG <参数名>[=<默认值>]
Copy after login

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
Copy after login

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}
Copy after login

VOLUME anonymous volume

VOLUME ["<路径1>", "<路径2>"...]
VOLUME <路径>
Copy after login

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 <端口1> [<端口2>...]
Copy after login

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 : at runtime.

-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 <工作目录路径>
Copy after login

Example 1:

WORKDIR /app

RUN echo "hello" > world.txt
Copy after login

Example 2:

WORKDIR /a
WORKDIR b
WORKDIR c

RUN pwd

## RUN pwd 的工作目录为 /a/b/c
Copy after login

USER Specify the current user

USER <用户名>[:<用户组>]
Copy after login

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" ]
Copy after login

HEALTHCHECK tells Docker how to determine whether the status of the container is normal

HEALTHCHECK [选项] CMD <命令>:设置检查容器健康状况的命令
HEALTHCHECK NONE:如果基础镜像有健康检查指令,使用这行可以屏蔽掉其健康检查指令
Copy after login

Options:

--interval=<间隔>:两次健康检查的间隔,默认为 30 秒;
--timeout=<时长>:健康检查命令运行超时时间,如果超过这个时间,本次健康检查就被视为失败,默认 30 秒;
--retries=<次数>:当连续失败指定次数后,则将容器状态视为 unhealthy,默认 3 次
Copy after login

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 <其它指令>
Copy after login
# 举例如下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 的命令开始执行
Copy after login

LABEL 为镜像添加元数据

LABEL <key>=<value> <key>=<value> <key>=<value> ...
Copy after login
# 标注镜像的作者

LABEL org.opencontainers.image.authors="yeasy"
Copy after login

SHELL 指定执行shell命令的参数

SHELL ["可执行程序", "参数"]
Copy after login
SHELL ["/bin/sh", "-c"]

RUN lll ; ls             # 这里的shell命令将通过 /bin/sh -c 的方式执行
Copy after login

推荐学习:《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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to update the image of docker How to update the image of docker Apr 15, 2025 pm 12:03 PM

The steps to update a Docker image are as follows: Pull the latest image tag New image Delete the old image for a specific tag (optional) Restart the container (if needed)

How to exit the container by docker How to exit the container by docker Apr 15, 2025 pm 12:15 PM

Four ways to exit Docker container: Use Ctrl D in the container terminal Enter exit command in the container terminal Use docker stop &lt;container_name&gt; Command Use docker kill &lt;container_name&gt; command in the host terminal (force exit)

How to use docker desktop How to use docker desktop Apr 15, 2025 am 11:45 AM

How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

How to copy files in docker to outside How to copy files in docker to outside Apr 15, 2025 pm 12:12 PM

Methods for copying files to external hosts in Docker: Use the docker cp command: Execute docker cp [Options] &lt;Container Path&gt; &lt;Host Path&gt;. Using data volumes: Create a directory on the host, and use the -v parameter to mount the directory into the container when creating the container to achieve bidirectional file synchronization.

How to view the docker process How to view the docker process Apr 15, 2025 am 11:48 AM

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

You 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 a mirror in docker How to create a mirror in docker Apr 15, 2025 am 11:27 AM

Steps to create a Docker image: Write a Dockerfile that contains the build instructions. Build the image in the terminal, using the docker build command. Tag the image and assign names and tags using the docker tag command.

How to save docker image How to save docker image Apr 15, 2025 am 11:54 AM

To save the image in Docker, you can use the docker commit command to create a new image, containing the current state of the specified container, syntax: docker commit [Options] Container ID Image name. To save the image to the repository, you can use the docker push command, syntax: docker push image name [: tag]. To import saved images, you can use the docker pull command, syntax: docker pull image name [: tag].

See all articles