Search code examples
windowspowershelldockerdockerfiledocker-build

In a dockerfile, how to delete a directory and its contents from docker image? (windows)


I'm using the python:3.6.5-windowsservercore base image.

COPY . /app copies the build context into C:\app. This includes certain secret keys required for building the project.

After running the build, I want to delete keys folder (C:\app\keys), for this I use:

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

Note - I have also tried each of following alternatives:

RUN Remove-Item -Path C:\app\keys -Force
RUN RD /S /Q C:\app\keys

This gives me following error:

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

What is the way to delete directory inside the image?


Solution

  • Solution:

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

    There are 2 aspects to resolve this.

    1. Based on your base image, what is your default shell? Bash or powershell? In my case it was powershell, so there is no need to mention powershell.exe at the beginning of the command.

    2. The original command was incorrect RUN Remove-Item -Path C:\app\keys -Force because the folder had sub-folders and files. So you have to mention -Recurse