Nicky
Nicky

Reputation: 3817

How to use NPM Package Config Variables in Docker commands?

I have a package.json file with a single config variable for the app port:

package.json

...
"config":{
  "port": "3000"
},
...

I also have a script defined to run a docker image. Now, I'd like to use the config variable in the command where I run my docker image. From here I can see how to use npm config variables. So my script becomes:

package.json (same one)

....
"scripts": {
    "docker:run": "docker run --rm -it -p $npm_package_config_port:$npm_package_config_port my-app:latest"
}
...

However, the variable port is never interpolated. Instead, I get an error from Docker when running:

Invalid containerPort: $npm_package_config_port

Question

How do I use a npm variable in my docker command via npm scripts?

Thanks!

Upvotes: 4

Views: 4660

Answers (1)

mike
mike

Reputation: 5223

I have tried this with Node 4.7.3 and npm 2.15.11

package.json

{
  "config": {
    "port": 3000
  },
  "scripts": {
    "start": "echo $npm_package_config_port"
  }
}

Try running npm start and it should output the port 3000. If it does not work, try the following package.json

{
  "config": {
    "port": 3000
  },
  "scripts": {
    "start": "env"
  }
}

This will output all environment variables and you can check if the port variable is available.

I'm not sure but the environment variables support could have been added with a newer node/npm version compared to the one you're using. Paste the output of node -v and npm -v so that we can check.

Upvotes: 3

Related Questions