Search code examples
node.jsdockernginxdocker-multi-stage-build

Docker Nodejs Multi Stage build Error. Dist not found


FROM node:14.9-stretch-slim AS build
WORKDIR /usr/src/app
COPY ./package.json ./
RUN yarn
COPY . .
CMD ["yarn", "run", "build"]

FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=build /usr/src/app/dist /usr/share/nginx/html

This is my dockerfile. When I build it I get an error saying that dist not found.

COPY failed: stat /var/lib/docker/overlay2/e397e0fd69733a25f53995c12dfbab7d24ce20867fede11886d49b9537976394/merged/usr/src/app/dist: no such file or directory

Any idea why this is happening ?

Any help would be highly appreciated.

Thanks.


Solution

  • The problem here is using CMD instead of RUN at CMD ["yarn", "run", "build"]

    FROM node:14.9-stretch-slim AS build
    WORKDIR /usr/src/app
    COPY ./package.json ./
    RUN yarn
    COPY . .
    RUN yarn run build
    
    FROM nginx:alpine
    COPY nginx.conf /etc/nginx/nginx.conf
    COPY --from=build /usr/src/app/dist /usr/share/nginx/html
    

    Here are the docs for RUN and CMD

    From the docs about CMD:

    The main purpose of a CMD is to provide defaults for an executing container. These defaults can include an executable, or they can omit the executable, in which case you must specify an ENTRYPOINT instruction as well.

    From the docs about RUN:

    The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile.

    As you can see CMD is executed at runtime when running the container but RUN commands are used to build the docker image

    How to debug this next time?

    In your Dockerfile you can basically run any executable part of the image. So to check if the dist folder exists or what are the contents of it you could just use ls

    FROM node:14.9-stretch-slim AS build
    WORKDIR /usr/src/app
    COPY ./package.json ./
    RUN yarn
    COPY . .
    RUN yarn run build
    RUN ls -la dist 
    
    FROM nginx:alpine
    COPY nginx.conf /etc/nginx/nginx.conf
    COPY --from=build /usr/src/app/dist /usr/share/nginx/html