Search code examples
node.jsdockerexpressdockerfile

Node can't find index.js inside a Docker container


I am trying to use two steps of building an image for my express.js app, in order to make it small and efficient as possible.

Dockerfile:

FROM node:alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# second step:
FROM node:alpine
WORKDIR /app
COPY --from=build /app/build /app
COPY --from=build /app/package*.json ./
RUN npm install --only=production
EXPOSE 3001
CMD ["node", "/app/build/index.js"]

But when I added the second step, node cannot find the file /app/build/index.js even though it's there:

enter image description here

Files in the container that was generated:

enter image description here

What did I do wrong?


Solution

  • You're copying from /app/build to /app in the final image with

    COPY --from=build /app/build /app
    

    so that's where the file is located.

    You can use a relative path to make your CMD simpler and use

    CMD ["node", "./index.js"]
    

    or with an absolute path use

    CMD ["node", "/app/index.js"]