Home > OS >  Use docker run command to initialize a project
Use docker run command to initialize a project

Time:02-05

I am looking for a way to initialize projects using the docker run command. I will be using node as an example.

Attempt

This is the command I tried.

docker run --rm -it -v "$PWD":/usr/app -w "/usr/app" --name foo_bar node:lts "npm init"

This however results in this error.

node:internal/modules/cjs/loader:1050
throw err;
^

Error: Cannot find module '/npm init'
at Module._resolveFilename (node:internal/modules/cjs/loader:1047:15)
at Module._load (node:internal/modules/cjs/loader:893:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}

Node.js v18.14.0

Not sure why it is complaining about '/npm init' so an explanation of what is really going wrong here is also welcome.

Expected Result

The npm init cli tool would start asking me to set the project name, version, et cetera and the following output would be in my current output directory.

I tried a variant of the command

docker run --rm -it -v "$PWD":/usr/app -w "/usr/app" --name foo_bar node:lts bash

This connects me to the container where I have run npm init to create the project which works but I want to do these in one go.

CodePudding user response:

enter image description here

Fix:

docker run --rm -it -v "$PWD":/usr/app -w "/usr/app" --name foo_bar node:lts npm init

Now, why does "npm init" give an error Error: Cannot find module '/npm init' but not command not found. It's because of the way node:lts image is built. If you look at node's Dockerfile on github at the bottom there are two lines.

ENTRYPOINT ["docker-entrypoint.sh"]

CMD [ "node" ]

node image's ENTRYPOINT executes "docker-entrpoint.sh" file and it's parameter is "node". On inspecting docker-entrypoint.sh

There's a comment

# Run command with node if the first argument contains a "-" or is not a system command.

This is reason why you get Module not found error when you write "npm init" as it's not system command it is run with node. But when its a system command it executes it as is.

  • Related