eks
eks

Reputation: 141

Conditional CMD in Docker

I'd like to run CMD ["npm", "run", "dev"] if a dev script is present in package.json, otherwise CMD ["npm", "start"]

Is there an idiomatic docker way for doing this? I suppose my CMD could be a bash script which checks for the presence of 'npm run dev'. Is there a cleaner way to do it than that?

Upvotes: 14

Views: 10735

Answers (4)

mmm
mmm

Reputation: 1436

If CMD is the only place you want to be different based on the node environment, then it is pretty straightforward. This is what I use sometimes:

CMD yarn "$(if [ $NODE_ENV = 'production' ] ; then echo 'start' ; else echo 'dev'; fi)"

Note that this is yarn, but you can change that to npm

Then the mentioned scripts (yarn start and yarn dev) will be triggered based on the value of NODE_ENV.

NODE_ENV is set to 'production' by default in most cloud providers BTW.

Upvotes: 2

adrihanu
adrihanu

Reputation: 1433

You could dynamically create a bash script containing appropriate command:

RUN bash -c "if npm run | grep -q dev ; then echo npm run dev > run.sh; else echo npm start > run.sh; fi; chmod 777 run.sh;"
CMD ./run.sh
  • if npm run | grep -q dev will check if dev script is present in package.json. Running npm run with no arguments will list all runable scripts and grep -q dev will return true only if dev is among them.

  • echo command > run.sh will create a file with provided command

  • chmod 777 run.sh will make the run.sh executable

  • CMD ./run.sh will execute created file

Upvotes: 9

yamenk
yamenk

Reputation: 51778

The Dockerfile syntax does not cover that such use case. You have to rely on scripts to achieve that.

Upvotes: 1

Ravindu Nirmal Fernando
Ravindu Nirmal Fernando

Reputation: 4822

Reading your package.json within your Dockerfile won't make any sense. What you can do is having separate Dockerfiles for dev environment and another Dockerfile which doesn't contain "dev" command. This way would provide you more control over the Docker images that you are building as well.

Upvotes: -1

Related Questions