Dockerizing a Node.js Script

We’ve seen how simple it is to Dockerize a compiled Go program. The image running the program doesn’t even need the Go compiler installed—just the binary!

Languages like JavaScript (Node.js), Python, Ruby, and PHP have runtime dependencies. To show you what this means, let’s Dockerize a JavaScript script instead of Python!

The JavaScript Code (main.js)

This script reads a text file and counts the occurrences of words.

const fs = require("fs");

function main() {
  const bookPath = "books/frankenstein.txt";
  const text = fs.readFileSync(bookPath, "utf8");
  const numWords = text.trim().split(/\s+/).length;

  console.log(`--- Begin report of ${bookPath} ---`);
  console.log(`${numWords} words found in the document\n`);

  console.log("--- End report ---");
}

main();

The Missing Runtime Error

If we try to Dockerize this exactly like we did the Go binary, using a plain Debian image:

# Dockerfile.js
FROM debian:stable-slim
COPY main.js main.js
COPY books/ books/
CMD ["node", "main.js"]

If you build and run this:

docker build -t bookbot -f Dockerfile.js .
docker run bookbot

You will get an error! The problem is our base image doesn’t have the node interpreter installed, so it can’t execute the script.

The Solution

We need an environment with Node.js installed. We have two options:

  1. Use RUN commands in our Dockerfile to install Node.js manually using apt-get or apk.
  2. (Better Option) Use an official Node.js base image!

Let’s update our Dockerfile.js to use an official Node image:

# Use the official Node.js image as the base
FROM node:20-slim

# Copy our application files
COPY main.js main.js
COPY books/ books/

# Run the script
CMD ["node", "main.js"]

Rebuild the image and run it:

docker build -t bookbot -f Dockerfile.js .
docker run bookbot

It works! We’ve bundled up the JavaScript script, its required data, and its required Node.js runtime all into a nice little container image.