How to add latest node to ubuntu docker

2021-06-26

I had a headache trying to do this, the snippets were often out of date and no one explained the snippets enough for me to be able to figure out how to fix issues with the snippets.

So here I present my solution but I'll explain what it's doing.

I am assuming you already have a Dockfile setup, these commands are added to your Dockerfile.

The problem

The version of node in the ubuntu repo, which is called nodejs and not node BTW, is old. So if your trying to do something with a Ubuntu image that needs a recent node version it can be tricky to get working.

The issue with some of the methods I found was they didn't install updates with the apt repo which led to issues with permissions which make things more complicated. Installing an updated version via the repo avoided all those problems.

The solution

So what you need to do is to add a updated source for node to APT. For this we have this repo nodesource/distributions which contains binaries for Ubuntu. They provide scripts that add the source to APT allowing you to then install with APT as normal.

So you go to the README and pick the node version you want to install and grab the snippet for the no "No root privileges". With docker, the commands are run as root.

https://github.com/nodesource/distributions#installation-instructions-1

This is the command for installing v16

# No root privileges
curl -fsSL https://rpm.nodesource.com/setup_16.x | sudo bash -

We then of cause need to add run the the beginning in a Dockerfile

RUN curl -fsSL https://deb.nodesource.com/setup_16.x | bash -

As it uses CURL we need to install curl first. Its good to update the APT sources before we install anything so we know we have the latest source for it. The -y means that it wont ask us anything when the Dockerfile builds. If you don't add that you'll get the interactive install with "Would you like to install...".

RUN apt-get update
RUN apt-get -y install curl

Then we can add the script which adds the new source for nodejs

RUN curl -fsSL https://deb.nodesource.com/setup_16.x | bash -
RUN apt-get -y install nodejs

echoing out the version shows us that it's definitely worked. If you change the user in the Dockerfile, you can echo out after that to make sure your user has the latest version aswell.

RUN node --version
RUN npm --version

All together

## Installs the latest version of node
RUN apt-get update
RUN apt-get -y install curl
RUN curl -fsSL https://deb.nodesource.com/setup_16.x | bash -
RUN apt-get -y install nodejs

RUN node --version
RUN npm --version

Gotchas

Don't try to install npm seperately as it comes with nodejs and if you do it will create a confusing error.

Make sure you run this snippet before you change the user.