Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run custom script after docker container startup

I have the following nodejs dockerfile:

# pull image
FROM node:13.12.0-alpine

# set working directory
WORKDIR /app

# add `/app/node_modules/.bin` to $PATH
ENV PATH /app/node_modules/.bin:$PATH

# install app dependencies
COPY package.json ./
COPY package-lock.json ./
RUN npm install

# add app
COPY . ./

# start app
CMD node server dev

I need to dynamically run a custom JS script inside the container after start up. How can I achieve this?

UPDATE: I tried adding the following entry point after CMD, but neither CMD not ENTRYPOINT was executed:

ENTRYPOINT node customScript.js

Added a wrapper shell script (startup.sh) to include both commands:

#!/bin/sh

nohup node server dev > startup.log && node data/scripts/custom.js > custom.log

Replaced CMD with:

CMD ["./startup.sh"]

This only executes the first command in the shell and not the second. I also don't see the output-redirect log files being created in the container.

like image 911
sotn Avatar asked Mar 01 '23 10:03

sotn


2 Answers

ideally, you should be running the process of nohup in background

there is no issue due to CMD or ENTRYPOINT

#!/bin/sh

nohup node server dev > startup.log && node data/scripts/custom.js > custom.log

use & last at your nohup command to start the process into backgroud mode

nohup ./yourscript &

or

nohup command &

after this you can run the node command

sh example

nohup nice "$0" "calling_myself" "$@" > $nohup_out &
node index.js
sleep 1
tail -f $nohup_out
like image 185
Harsh Manvar Avatar answered Apr 02 '23 15:04

Harsh Manvar


You should use a supervisor to run multiple processes in a single container. They will/may also auto-restart died process again. Without a supervisor, your processes may be messed up.

Ex:

In my case, I use s6 in the project alpine-s6-nginx-php to run processes in a single container. The project has an OOP-like inheritance model from:

  • base the image alpine-s6-base
  • to alpine-s6-nginx
  • to alpine-s6-nginx-php.

Base image prepares the s6 setup, nginx image adds nginx process and final alpine-s6-nginx-php image adds php-fpm7 process. You may check these repos and s6 supervisor. It is not needed to separate layers for each process, all processes can be added in a single Dockerfile. And also you may use s6 alternatives like systems or etc.

TLDR; you can use s6-overlay to build s6 supervised container images easily.

like image 26
raxetul Avatar answered Apr 02 '23 16:04

raxetul