I am pushing all the source code inside then i’m creating a build out of it. Then i want to delete all the sourceCode inside the image. How can i do that.
FROM node:18.17.1
WORKDIR /app
COPY package*.json ./
COPY tsconfig.json ./
COPY src/ ./src/
COPY .env ./
RUN npm install
RUN npm run build
RUN User shopt -s extglob ; rm -rf !(build) # this give me errors
EXPOSE 4000
CMD ["node", "build/app.js"]
also this is not working too.
find . -mindepth 1 ! -name 'build' -exec rm -r {} +
this gives me filenames and says file can’t deleted because not exists…
so annoying
2
Answers
You need to add:
before
rm
command.You should use a Docker multi-stage build for this case. Instead of trying to delete files from an image, tell Docker to start over from a new image, and then copy in the built files from the old image.
Internally, a Docker image consists of a sequence of layers. Whenever you have a
RUN
command, Docker keeps all of the previous image and also records whatever’s changed from the new step. That is, a newRUN
line always makes the image larger, even if youRUN rm ...
, and a motivated user can extract the deleted content from the previous layer.The multi-stage build starts over from a base image, re-installs library dependencies, and then
COPY --from=build
the built application. The original source code was never in this image, so it’s not part of the final image. This sequence also means that you can install only thedependencies
into the final image’snode_modules
directory, and not thedevDependencies
. I also haven’t copied the Typescript setup into the final image because it’s not needed there.