全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-21 6 分钟 ✍️ juanwangdev

构建自定义镜像

使用 Dockerfile 可构建自定义镜像,下面介绍构建命令与上下文概念。

docker build 命令

基本用法

Bash
# 从当前目录构建
docker build -t my-app:1.0 .

# 指定 Dockerfile 路径
docker build -t my-app:1.0 -f Dockerfile.prod .

# 指定构建参数
docker build -t my-app:1.0 --build-arg NODE_ENV=production .

标签管理

Bash
# 多个标签
docker build -t my-app:1.0 -t my-app:latest .

# 指定仓库和标签
docker build -t registry.example.com/my-app:v1.0 .

构建上下文

Bash
# 构建上下文是当前目录(包括子目录)
docker build -t my-app .

# 上下文中的所有文件发送给 Docker Daemon
# .dockerignore 用于排除不需要的文件

构建上下文决定了 COPY 指令可访问的文件范围。不要在项目根目录执行 build,应限定在必要目录。

.dockerignore 文件

Bash
# 排除 node_modules
node_modules/

# 排除 .git
.git/
.gitignore

# 排除日志
*.log
logs/

# 排除环境变量
.env
.env.*

# 排除 Dockerfile 本身
Dockerfile*
docker-compose*

.dockerignore 减少构建上下文大小,加速构建,避免拷贝无关文件。

构建过程

dockerfile
docker build -t my-app:1.0 .

# 输出示例
[+] Building 2.3s (10/10) FINISHED
 => [internal] load build definition from Dockerfile           0.1s
 => => transferring dockerfile: 37B                            0.0s
 => [internal] load .dockerignore                              0.1s
 => => transferring context: 2B                                0.0s
 => [1/5] FROM docker.io/library/node:18-alpine               0.0s
 => [2/5] WORKDIR /app                                         0.0s
 => [3/5] COPY package*.json ./                               0.1s
 => [4/5] RUN npm ci --only=production                        1.5s
 => [5/5] COPY . .                                             0.1s
 => exporting to image                                         0.5s
 => => naming to docker.io/library/my-app:1.0                  0.5s

构建缓存

Docker 利用缓存加速重复构建:

Bash
# 利用缓存:先拷贝依赖文件,再安装
COPY package*.json ./
RUN npm ci --only=production  # 缓存命中

# 破坏缓存:改变顺序
COPY . .  # 任何代码变更都会破坏后续缓存
RUN npm ci --only=production  # 缓存失效,重新执行

禁用缓存

dockerfile
# 不使用缓存,重新构建所有层
docker build --no-cache -t my-app:1.0 .

构建参数

Bash
# Dockerfile 中使用 ARG
ARG NODE_ENV=production
ARG VERSION=1.0

ENV APP_VERSION=$VERSION
ENV NODE_ENV=$NODE_ENV

RUN echo "Building version $VERSION"
text
# 构建时传入参数
docker build --build-arg NODE_ENV=development --build-arg VERSION=2.0 -t my-app:2.0 .

ARG 仅在构建时可用,ENV 在构建和运行时均可用。

要点总结

  • docker build -t 名称:标签 . 从当前目录构建
  • 构建上下文是当前目录,使用 .dockerignore 排除无关文件
  • Docker 利用层缓存加速构建,合理安排指令顺序提升缓存命中
  • ARG 是构建时参数,构建后不可访问;ENV 在运行时也可访问
  • --no-cache 禁用缓存强制重建,-f 指定 Dockerfile 路径

📝 发现内容有误?点击此处直接编辑

← 上一篇 WORKDIR 与 ENV 指令
下一篇 → MySQL/PostgreSQL 容器部署
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库