Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to generate a package.json file on local machine in current directory, using single line "docker run" command from node image

I’m trying to run the npm init command to spit out a package.json file on my local machines current working directory, by running a Node image on docker.

I have attempted to do it like so but haven’t had the desired results described above.

docker run -d -v $pwd:~/tmp node:18-alpine3.14 "cd ~/tmp && npm init"

The command I’m passing above at the end gets passed to the Node application rather than the container it is held inside. I know this because the container exits with Error: Cannot find module '/cd ~/tmp && npm init'.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can i execute commands for the container to receive rather than Node inside it in this example?

>Solution :

You cloud use sh -c "some command" as command, but I think it’s cleaner, like below.

Using the workdir flag and also using your local user and group id so that you don’t have to fix the permissions later on.

docker run --rm \
  --user "$(id -u):$(id -g)" \
  --workdir /temp \
  --volume "$PWD:/tmp" \
  --tty
  --interactive
  node:18-alpine3.14 npm init

I am also using tty and interactive so that you can answer the questions from npm init. If you dont want questions, use npm init -y.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading