在一个 Dockerfile 中,如何从 Docker 镜像中删除一个目录及其内容?(Windows)

3

我正在使用 python:3.6.5-windowsservercore 基础镜像。

COPY . /app 将构建上下文复制到 C:\app 中。这包括构建项目所需的某些秘钥。

在运行构建之后,我想要删除 keys 文件夹(C:\app\keys),因此我使用以下命令:

RUN powershell.exe Remove-Item -Path C:\app\keys -Force

注意-我还尝试了以下每个替代方案:
RUN Remove-Item -Path C:\app\keys -Force
RUN RD /S /Q C:\app\keys

这导致我出现以下错误:
Step 10/14 : RUN powershell.exe Remove-Item -Path C:\app\keys -Force
 ---> Running in 4e22124332b1
Remove-Item : Object reference not set to an instance of an object.
At line:1 char:1
+ Remove-Item -Path C:\app\keys -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Remove-Item], NullReferenceEx
   ception
    + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShe
   ll.Commands.RemoveItemCommand

The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; powershell.exe Remove-Item -Path C:\app\keys -Force' returned a non-zero code: 1

如何删除镜像内的目录?


只是确认一下,以防对 Powershell 的 cmdlet 和参数解析产生任何影响,因为我可以在错误输出中看到它,但通常我会看到 docker 命令包含 -Command 参数用于 powershell.exe。像这样:RUN powershell.exe -Command Remove-Item -Path "C:\app\keys" -Force。如果你已经尝试过这种方式,请原谅。如果你已经运行了像 SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"] 这样的命令,你只需要运行 RUN Remove-Item -Path C:\app\keys -Force - Ash
  1. 我刚试过使用-Command;我得到了相同的错误。
  2. 不,我没有运行类似SHELL的命令。
- variable
我确认,你只需要在你的dockerfile中添加RUN Remove-Item -Path C:\app\keys -Force。你可能可以在这里找到一些帮助:https://github.com/Drylm/rmq-win/blob/master/Dockerfile.3.7.7 - Bhaal22
不,这是同样的错误。 - variable
1个回答

2

解决方案:

RUN Remove-Item -Path C:\app\keys -Force -Recurse

有两个方面需要解决。
  1. 基于你的基础镜像,你的默认shell是什么?Bash还是powershell?在我的情况下,它是powershell,因此在命令开头没有必要提到powershell.exe。

  2. 原始命令是不正确的RUN Remove-Item -Path C:\app\keys -Force,因为该文件夹有子文件夹和文件。所以你必须提到 -Recurse


"-Recurse"有bug,对于大型树结构无法正常工作。 - mip

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接