Search code examples
node.jsbashdockerdocker-entrypoint

Running bash script in a dockerfile


I am trying to run multiple js files in a bash script like this. This doesn't work. The container comes up but doesn't run the script. However when I ssh to the container and run this script, the script runs fine and the node service comes up. Can anyone tell me what am I doing wrong?

Dockerfile

FROM node:8.16

MAINTAINER Vivek

WORKDIR /a

ADD . /a
RUN cd /a && npm install

CMD ["./node.sh"]

Script is as below

node.sh

#!/bin/bash

set -e

node /a/b/c/d.js &

node /a/b/c/e.js &

Solution

  • As @hmm mentions your script might be run, but your container is not waiting for your two sub-processes to finish.

    You could change your node.sh to:

    #!/bin/bash
    
    set -e
    
    node /a/b/c/d.js &
    pid1=$!
    
    node /a/b/c/e.js &
    pid2=$!
    
    wait pid1
    wait pid2
    

    Checkout https://stackoverflow.com/a/356154/1086545 for a more general solution of waiting for sub-processes to finish.

    As @DavidMaze is mentioning, a container should generally run one "service". It is of course up to you to decide what constitutes a service in your system. As described officially by docker:

    It is generally recommended that you separate areas of concern by using one service per container. That service may fork into multiple processes (for example, Apache web server starts multiple worker processes). It’s ok to have multiple processes, but to get the most benefit out of Docker, avoid one container being responsible for multiple aspects of your overall application.

    See https://docs.docker.com/config/containers/multi-service_container/ for more details.