docker - passing file name as arguments to nodejs application

9/13/2019

I have to convert an existing nodejs application to run on the RedHat OpenShift container platform. Currently, the application is run as follows:

node index.js $HOME/arg1.json $HOME/arg2.json

Using files for arguments is important for this application since the number of arguments are quite large.

How can I ensure that the container version is also run off of the configuration files?

-- cogitoergosum
arguments
docker
kubernetes
node.js
openshift

2 Answers

9/13/2019

You can do this with the help of ENV, build the Dockerfile with some default ENV then if you need to overide with some other file, overide them at run time.

FROM node:alpine
ENV HOME="/app"
ENV file1="file1"
ENV file2="file2"
COPY index.js $HOME/index.js
CMD ["/bin/sh", "-c", "node $HOME/index.js $HOME/$file1 $HOME/$file2"]

index.js

const args = process.argv;
console.log(args);

output of nodejs script

[ '/usr/local/bin/node', '/app/index.js', '/app/file1', '/app/file2' ]

To overide filename for different config

docker run --rm -it -e file1="stage.json" abc

Now the output will be

[
  '/usr/local/bin/node',
  '/app/index.js',
  '/app/stage.json',
  '/app/file2'
]

If you are expecting big number of argument then better follow this method.

FROM node:alpine
ENV HOME="/app"
COPY index.js $HOME/index.js
RUN echo $'#!/bin/sh \n\
     node $HOME/index.js $@' >> /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

So now pass as many argument as you want, docker run

docker run --rm -it -e file1="stage.json" abc "$HOME/arg1.json $HOME/arg2.json $HOME/arg3.json"

node args result will be

[
  '/usr/local/bin/node',
  '/app/index.js',
  '/home/adiii/arg1.json',
  '/home/adiii/arg2.json',
  '/home/adiii/arg3.json'
]
-- Adiii
Source: StackOverflow

9/13/2019

You mention in your first comment the requirement that filenames be specified at runtime. Something like this will work:

ENV work /app
WORKDIR $work
COPY ./arg1.json ./arg2.json $work/

CMD["node", "index.js", "./arg1.json", "arg2.json"]

Runtime command:

docker run -v $(pwd)/myarg1.json:/app/arg1.json -v $(pwd)/myarg2.json:/app/arg2.json <image> 
-- Rondo
Source: StackOverflow