0

I have a simple node setup using node cluster that forks worker processes. When I run it directly using node index.js everything works just fine. However, when I create a docker container and try to run in from there, I get an error saying cannot read property of undefined when reading cluster.worker.id

This is my index.js

import cluster from "cluster";
import express from "express";
import config from "./config.js";
import monitorRoutes from "./monitor/routes.js";
import spawnQueue from "./queues/index.js";

if (cluster.isPrimary) {

  for (let i = 0; i < config.NUMBER_OF_WORKERS; i++) {
    cluster.fork();
  }

} else {
  
  const app = express();

  app.use("/", monitorRoutes);

  // create a queue
  const queue = spawnQueue(cluster.worker.id); // this is the problem line

  // on post requests add a task to the queue
  app.post("/", (req, res) => {
    queue.add(
      {},
      {
        attempts: config.DEFAULT_ATTEMPTS,
      }
    );
    // send the notification with queue id
    res.json({
      message: `Job added to be processed by worker ${cluster.worker.id}`,
    });
  });


  app.listen(5000, () => {
    console.log("Server is running on port 5000");
  });
}

This is the Dockerfile

FROM node:12.18.3
    
LABEL version="1.0"
LABEL description="..."
LABEL maintainer = ["<my-email>"]

WORKDIR /app

COPY ["package.json", "package-lock.json", "./"]
RUN ls
RUN npm install
COPY . .

EXPOSE 5000

CMD ["node", "index.js"]

When I create the image with docker build and then run it with docker run it stops at the cluster.worker.id line at says that cluster.worker is undefined. However, this all works perfectly fine outside of docker.

Do I have a problem in my Dockerfile or is there some additional setup I need to run when using node cluster?

  • can you show your package.json file ? You are using import syntax (esm) with an older version of node (12). Can you check if `cluster` is resolved to an object ? You can try before accessing cluster.worker.id assert `if (cluster.isWorker) {}` – Jone Polvora Mar 27 '22 at 01:48
  • Thanks, your comment helped me fix this actually. Turns out the problem was that I was using cluster.isPrimary check and that only works in node 16 and higher. So the solution was to either use cluster.isMaster or pull a different version of node – NoncomissionedRush Mar 27 '22 at 21:43
  • yes, make sure your local node version (in your environment) is the same that you're requiring in your .Dockerfile, so you get the same behaviour in all cases. – Jone Polvora Mar 30 '22 at 00:50

0 Answers0