skip to Main Content

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


  1. You need to add:

    shopt -s extglob
    

    before rm command.

    Login or Signup to reply.
  2. 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.

    # Build stage is exactly what you show already
    FROM node:18.17.1 AS build
    
    WORKDIR /app
    
    COPY package*.json ./
    RUN npm install  # move this earlier to avoid reinstalling packages on rebuilds
    
    COPY tsconfig.json ./
    COPY src/ ./src/
    COPY .env ./
    
    RUN npm run build
    
    # For the second stage, re-install packages and
    # copy in the built application
    FROM node:18.17.1
    WORKDIR /app
    ENV NODE_ENV=production
    COPY package*.json ./
    RUN npm install
    
    COPY .env ./
    COPY --from=build /app/build/ ./build/
    
    # Then set metadata to run the image
    EXPOSE 4000
    CMD ["node", "build/app.js"]
    

    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 new RUN line always makes the image larger, even if you RUN 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 the dependencies into the final image’s node_modules directory, and not the devDependencies. I also haven’t copied the Typescript setup into the final image because it’s not needed there.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search