Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 616
eks Avatar asked Dec 14 '17 02:12

eks


2 Answers

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

like image 99
adrihanu Avatar answered Oct 18 '22 21:10

adrihanu


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

like image 32
yamenk Avatar answered Oct 18 '22 22:10

yamenk