How to only install production dependencies and then some, but without any development dependencies?

Viewed 333

Given the following Dockerfile and package.json, how do I get my image to only have what is defined as production dependencies in the package.json and the one additional dependency defined in the RUN --no-save layer, but not any of the development dependencies?

FROM node:16.14.2-alpine3.15
WORKDIR /opt/asd
COPY ./package.json .
RUN npm install --production
RUN npm install --no-save typescript
{
  "devDependencies": {
    "express": "4.17.3"
  },
  "dependencies": {
    "ramda": "0.28.0"
  }
}

Running docker build . produces an image that has node_modules containing not only the deps I wanted but also the development dependencies. What do I need to change in the Dockerfile to avoid this?

1 Answers

You can use bash conditionals syntax, but you also need to define $NODE_ENV as environment variable:

RUN if [ "$NODE_ENV" = "production" ]; \
    then npm install --only=production; \
    else npm install; \
    fi
Related