Files
docker_practice/image/dockerfile/label.md
2026-01-30 16:48:39 -08:00

3.8 KiB
Raw Blame History

LABEL 为镜像添加元数据

基本语法

LABEL <key>=<value> <key>=<value> ...

LABEL 指令以键值对的形式给镜像添加元数据。这些数据不会影响镜像的功能,但可以帮助用户理解镜像,或被自动化工具使用。


为什么需要 LABEL

  1. 版本管理记录版本号、构建时间、Git Commit ID
  2. 联系信息:维护者邮箱、文档地址、支持渠道
  3. 自动化工具 CI/CD 工具可以读取标签触发操作
  4. 许可证信息:声明开源协议

基本用法

定义单个标签

LABEL version="1.0"
LABEL description="这是一个 Web 应用服务器"

定义多个标签(推荐)

LABEL maintainer="user@example.com" \
      version="1.2.0" \
      description="My App Description" \
      org.opencontainers.image.authors="Yeasy"

💡 包含空格的值需要用引号括起来。


常用标签规范 (OCI Annotations)

为了标准和互操作性,推荐使用 OCI Image Format Specification 定义的标准标签:

标签 Key 说明 示例
org.opencontainers.image.created 构建时间(RFC 3339) 2024-01-01T00:00:00Z
org.opencontainers.image.authors 作者/维护者 support@example.com
org.opencontainers.image.url 项目主页 https://example.com
org.opencontainers.image.documentation 文档地址 https://example.com/docs
org.opencontainers.image.source 源码仓库 https://github.com/user/repo
org.opencontainers.image.version 版本号 1.0.0
org.opencontainers.image.licenses 许可证 MIT
org.opencontainers.image.title 镜像标题 My App
org.opencontainers.image.description 描述 Production ready web server

示例

LABEL org.opencontainers.image.authors="yeasy" \
      org.opencontainers.image.documentation="https://yeasy.gitbooks.io" \
      org.opencontainers.image.source="https://github.com/yeasy/docker_practice" \
      org.opencontainers.image.licenses="MIT"

MAINTAINER 指令(已废弃)

旧版本的 Dockerfile 中常看到 MAINTAINER 指令:

# ❌ 已弃用
MAINTAINER user@example.com

现在推荐使用 LABEL

# ✅ 推荐
LABEL maintainer="user@example.com"
# 或
LABEL org.opencontainers.image.authors="user@example.com"

动态标签

配合 ARG 使用,可以在构建时动态注入标签:

ARG BUILD_DATE
ARG VCS_REF

LABEL org.opencontainers.image.created=$BUILD_DATE \
      org.opencontainers.image.revision=$VCS_REF

构建命令:

$ docker build \
  --build-arg BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ') \
  --build-arg VCS_REF=$(git rev-parse --short HEAD) \
  .

查看标签

docker inspect

查看镜像的标签信息:

$ docker inspect nginx --format '{{json .Config.Labels}}' | jq
{
  "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
}

过滤器

可以使用标签过滤镜像:

# 列出作者是 yeasy 的所有镜像
$ docker images --filter "label=org.opencontainers.image.authors=yeasy"

# 删除所有带有特定标签的镜像
$ docker rmi $(docker images -q --filter "label=stage=builder")

本章小结

要点 说明
作用 添加 key-value 元数据
语法 LABEL k=v k=v ...
规范 推荐使用 OCI 标准标签
弃用 不要再使用 MAINTAINER
查看 docker inspect

延伸阅读