Reputation: 2041
I have an extremely simple Docker app that uses json-server
as a fake backend, but I can't get it to work for some bizarre reason. Here's the Docker file:
The directory I'm building this in contains a Dockerfile, server.js, and db.json.
FROM node:latest
RUN npm install json-server -g
WORKDIR /app
ADD . /app
EXPOSE 3004
CMD ["node", "server.js"]
The json-server itself is dead simple:
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(router)
server.listen(3004, () => {
console.log('JSON Server is running')
})
Docker is able to build this image. But when I try to run it, I get the following error:
node:internal/modules/cjs/loader:1042
throw err;
^
Error: Cannot find module 'json-server'
Require stack:
- /app/server.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1039:15)
at Module._load (node:internal/modules/cjs/loader:885:27)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/app/server.js:1:20)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Module._load (node:internal/modules/cjs/loader:922:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/app/server.js' ]
}
Why can't it find the json-server
module, especially when I just installed it globally? I'm so confused by this since it couldn't be simpler.
Upvotes: 2
Views: 743
Reputation: 33
Using latest alpha version of json-server was not working for me as well.
Solution was downgrading version "json-server": "^0.17.0"
Upvotes: 3
Reputation: 25070
The node image doesn't set the NODE_PATH environment variable, so node can't find globally installed modules.
Since containers are only meant to run a single process, it doesn't really make sense to install things globally.
If you install the module non-globally in your /app
directory, it works:
FROM node:latest
WORKDIR /app
RUN npm install json-server
ADD . /app
EXPOSE 3004
CMD ["node", "server.js"]
Upvotes: 1