You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Kaniko执行mkdir失败:提示目录已存在但实际不存在

使用Kaniko构建Docker镜像时目录已存在错误的排查方案

问题描述

我在Jenkins节点上使用Kaniko执行如下Dockerfile:

FROM docker.mycompany.io/adoptopenjdk/openjdk11:jre-11.0.11_9-alpine

COPY app.jar app.jar

RUN mkdir /some-directory

执行后收到错误:

mkdir: can't create directory '/some-directory': File exists

已确认基础镜像adoptopenjdk/openjdk11:jre-11.0.11_9-alpine中不存在/some-directory,但Kaniko仍提示该目录已存在。使用的Kaniko命令为:

/kaniko/executor \
  --context dir://myproject/src/main/docker \
  --dockerfile myproject/src/main/docker/Dockerfile \
  --destination docker-staging.docker.mycompany.io/foo/myproject:111.222.333 \
  --registry-certificate docker-staging.docker.mycompany.io=/etc/ssl/certs/mycompany.crt \
  --verbosity=debug \
  --cache=true

排查与解决方法

1. 禁用Kaniko缓存重试

你开启了--cache=true,Kaniko可能复用了之前构建产生的中间层缓存,这些缓存层中可能已经创建了/some-directory。临时关闭缓存重新构建:

/kaniko/executor \
  --context dir://myproject/src/main/docker \
  --dockerfile myproject/src/main/docker/Dockerfile \
  --destination docker-staging.docker.mycompany.io/foo/myproject:111.222.333 \
  --registry-certificate docker-staging.docker.mycompany.io=/etc/ssl/certs/mycompany.crt \
  --verbosity=debug \
  --cache=false

如果问题消失,说明是缓存导致的,可以清理Kaniko缓存后再重新启用缓存构建。

2. 检查构建上下文目录

构建上下文myproject/src/main/docker中如果存在some-directory,可能在Kaniko处理上下文时被意外映射或影响镜像构建。

  • 进入myproject/src/main/docker目录,执行ls -la查看是否存在some-directory。
  • 如果存在,删除该目录或修改Dockerfile中要创建的目录名称,再重新构建。

3. 检查Jenkins节点的挂载配置

Kaniko在Jenkins节点运行时,若宿主机的目录被挂载到Kaniko容器的根路径/下,可能导致容器内/some-directory实际来自宿主机。

  • 查看Jenkins中Kaniko容器的运行配置,确认没有将宿主机的/some-directory或其他包含该目录的路径挂载到容器内部。

4. 强制拉取最新基础镜像

可能存在本地缓存的基础镜像与你检查的版本不一致(比如标签被重新推送过)。在Kaniko命令中添加--pull参数强制拉取最新基础镜像:

/kaniko/executor \
  --context dir://myproject/src/main/docker \
  --dockerfile myproject/src/main/docker/Dockerfile \
  --destination docker-staging.docker.mycompany.io/foo/myproject:111.222.333 \
  --registry-certificate docker-staging.docker.mycompany.io=/etc/ssl/certs/mycompany.crt \
  --verbosity=debug \
  --cache=true \
  --pull

内容的提问来源于stack exchange,提问作者lance-java

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:52:38