In this article, I show you how to run NodeJS through Docker.
Step 1. Install Docker
- Browse to https://docs.docker.com/engine/installation/
- Install the version of Docker for your operating system
Step 2. Pull a node image
Open up a command / terminal window and run the following:
docker pull node:buster-slim
Step 3. Run your tests
If you have a NodeJS project with some tests, here is how you can run them through Docker:
- Change the directory to the root of your NodeJS project folder
- Run your tests with this command:
docker run -v "$PWD":/usr/src/app -w /usr/src/app node:buster-slim sh -c 'npm install && npm test'
Step 4. Understand the docker run command
In this step I’ll break down what the docker run command in the previous step actually does:
The docker run command sets up a shared volume using the -v flag.
$PWD means use present working directory – in other words the folder you are currently in
It then maps that folder to the folder within the docker container (/usr/src/app)
When node and npm are run inside the container, they will expect the root of the project to be in that folder
The -w flag sets the working directory inside the container.
The version of the node docker image that we’d like to use. In this case the version is
Buster is a version of Linux. Slim usually means the base image has been slimmed down to just the essentials. Which should cause it to load faster.
The image was already downloaded using the pull command. If it wasn’t you would have seen it download the first time you used the docker run command.
sh -c 'npm install && npm test'
This shells into the container and runs the command.
The command first runs npm install, then npm test.
Step 5. Confirm the results on your screen
After the command runs you should see the test results echoed to your screen. It should work exactly as if you were running node locally.
If you need to use a particular version of node, visit the official page for the docker image:
buster-slim with whatever version from the list that you need.
In this article I showed you how to run NodeJS locally, but through a docker container.
You also learned how to:
- Download a docker image of node using the
- Run a docker image with extra parameters
- Map a folder in a docker container to a local folder
- Set the working directory of a container through the command line
- Pass shell commands to a docker container and see their results locally
Sometimes you run into problems trying to install and run tools like NodeJS on your local machine. Or you may need to use a version that is different from what you have installed. A quick solution is to just run NodeJS through docker.
This article only showed one example of passing arguments to a NodeJS docker container. Any command you use locally to run npm or nodejs should work as well.
- How to Cross Compile for Raspberry Pi – my article on desertbot.io that shows how to cross compile using Docker
- hub.docker.com/_/node