How to remove directory/packages from prebuilt docker image pulled by Nix

Hey!

I have Nix to pull a prebuilt image, and I want to remove an unused directory from that image to make the image smaller, currently I am doing something like:

base_image = pkgs.dockerTools.pullImage {
    imageName = "base";
    ...
  };

image = pkgs.dockerTools.buildLayeredImage {
    name = "image";
    tag = "...";
    fromImage = base_image;
    maxLayers = ...;
    created = ...;
    contents = with pkgs.pkgsLinux; [
      curl
    ];
    extraCommands = ''
      // other commands 
     ... 
     // to remove the directory
     rm -rf ./directory/to/remove
    '';
  };

But this doesn’t work because extraCommands only executes on the top layer without access to other layers (i.e. layers with the docker image). When I do this it does nothing because ./directory/to/remove is not on the file system on the top layer.

Is there a way or walk around to remove something during build time?

Hey ho :wave:
Have you stumbled across nixpkgs/pkgs/build-support/docker/default.nix at 49cca7c950e786d9cb79cd8a45f2ad70010e51f7 · NixOS/nixpkgs · GitHub yet?

You could build/pull both images and merge them with pkgs.dockerTools.mergeImages and manipulate the merged image as it should only consist of a single layer, so all of your extraCommands can do their stuff.

IMO: The “proper” solution (non-Nix or Nix) would require a whitelist of your necessary files, copy them to your target image (built from scratch) without any bloat.