Asked to install Typescript when already installed when building Docker image
When you run (even outside Docker)
export NODE_ENV=production
npm install
it only installs the dependencies
from your package.json
and not the devDependencies
. On the other hand, you probably need the devDependencies
to get tools like typescript
.
The good solution here is to use a multi-stage build. The first stage installs all of the dependencies; the second stage copies out only what’s needed to run the application.
FROM gcr.io/companyX/companyX-node-base:12-alpine AS build
# Copy in only the parts needed to install dependencies
# (This avoids rebuilds if the package.json hasn’t changed)
COPY package.json package.lock .
# Install dependencies (including dev dependencies)
RUN npm install
# Copy in the rest of the project
# (include node_modules in a .dockerignore file)
COPY . .
# Build the project
RUN npm run build
# Second stage: runtime
FROM gcr.io/companyX/companyX-node-base:12-alpine
ENV NODE_ENV=production
# Again get dependencies, but this time only install
# runtime dependencies
COPY package.json package.lock .
RUN npm install
# Get the built application from the first stage
COPY --from=build /app/dist dist
# Set runtime metadata
EXPOSE 3000
CMD [ "npm", "start" ]
# CMD ["node", "dist/index.js"]
Note that this approach isn’t compatible with setups that overwrite the application content with arbitrary content from the host, or that try to store libraries in Docker volumes. The final image is self-contained and doesn’t require any host content, and can be run as-is on other systems without separately copying the source code.
I got the same error on deploying Next.js app on AWS Amplify and I didn't want to move typescript from devdependencies to dependencies.
My solution was to change the build setting from npm install
to
npm install --dev typescript && npm install
There must be same places for build settings in docker.
This will remove the error.