docker build 命令用于从 Dockerfile 构建 Docker 镜像。
docker build 命令通过读取 Dockerfile 中定义的指令,逐步构建镜像,并将最终结果保存到本地镜像库中。
语法
docker build [OPTIONS] PATH | URL | -
常用选项:
更多选项说明:
1、构建镜像
docker build -t myimage:latest .
这会从当前目录读取 Dockerfile 并构建一个名为 myimage:latest 的镜像。
2、指定 Dockerfile 路径
docker build -f /path/to/Dockerfile -t myimage:latest .
这会从 /path/to/ 目录读取 Dockerfile 并构建一个名为 myimage:latest 的镜像。
3、设置构建参数
docker build --build-arg HTTP_PROXY=http://proxy.example.com -t myimage:latest .
这会在构建过程中使用 HTTP_PROXY 环境变量。
4、不使用缓存层构建镜像
docker build --no-cache -t myimage:latest .
这会在构建镜像时忽略所有缓存层,确保每一步都重新执行。
实例 - 使用 Dockerfile 构建镜像
1、创建 Dockerfile,内容如下:
# Dockerfile 示例 FROM ubuntu:20.04 LABEL maintainer="yourname@example.com" RUN apt-get update && apt-get install -y nginx COPY index.html /var/www/html/index.html CMD ["nginx", "-g", "daemon off;"]
2、构建镜像
docker build -t mynginx:latest .
输出示例:
Sending build context to Docker daemon 3.072kB Step 1/5 : FROM ubuntu:20.04 20.04: Pulling from library/ubuntu ... Step 2/5 : LABEL maintainer="yourname@example.com" ... Step 3/5 : RUN apt-get update && apt-get install -y nginx ... Step 4/5 : COPY index.html /var/www/html/index.html ... Step 5/5 : CMD ["nginx", "-g", "daemon off;"] ... Successfully built 123456789abc Successfully tagged mynginx:latest
3、验证镜像
docker images
注意事项
REPOSITORY TAG IMAGE ID CREATED SIZE mynginx latest 123456789abc 10 minutes ago 200MB
docker build 命令是构建 Docker 镜像的核心工具,通过定义清晰的 Dockerfile,可以自动化地构建应用程序的运行环境和依赖。在使用时,确保合理设置选项和优化 Dockerfile,以提高构建效率和镜像质量。
返回:Docker 命令大全