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?