James Quigley's Blog

Specifying npm Version in Dockerfile

August 21, 2017

TL;DR

RUN npm i npm
RUN mv node_modules/npm /usr/local/lib/node_modules/npm
RUN rm -rf /usr/local/lib/node_modules/npm

Details

Each Node.js version ships with npm. Currently the LTS Node version (v6.11.2) ships with npm v3.10.10. But what if you want to use the latest features of npm 5.x.x with an older version of Node?

Outside of a container, this is simple. You install the Node version that you want (use nvm to easily swap between them) and then specify npm version.

npm i -g npm@5.3.0 //specific version
npm i -g npm       //for latest

Doing this inside a container, while possible, is a little bit trickier. You declare the version of Node you want to use with the “FROM” command.

FROM node:boron

But this comes with an old version of npm. If you try to upgrade as you normally would, you’ll run into an issue where the package “semver” can’t be found. The npm installation is bad. The solution:

RUN npm install npm@5.3.0
RUN rm -rf /usr/local/lib/node_modules/npm
RUN mv node_modules/npm /usr/local/lib/node_modules/npm

Install npm in the project, remove the global package, then move the local package to your global location. Now you have the Node version specified at the top, but the npm version you want, not the one bundled with Node.


Written by James Quigley, an SRE/DevOps Engineer, and general tech nerd. Views and opinions are my own. Check out my YouTube Channel or follow me on Twitter!