Matthis Kohli
Matthis Kohli

Reputation: 1995

How to make Docker restart a Container after a period of time?

How to restart a Node JS application running inside a docker container after a period of time without user input (Automated)?

I have a Docker Container with an application whose underlying architecture showed to hang once in a while. The idea is to simply restart the application after a period of time. This should all happen automated. Consider the following Dockerfile.

FROM node:6.11.1
ENV HOME=/usr/src/app/
# Create app directory
RUN mkdir -p $HOME
WORKDIR $HOME
COPY npm-shrinkwrap.json $HOME
RUN npm install
# Bundle app source
COPY . $HOME
EXPOSE 3000
CMD ["npm", "start"]

After npm start the application either was successfull or not. In most cases it runs successull. So for the other cases I would like to simply restart the whole application after a period of time.

Upvotes: 0

Views: 5272

Answers (2)

Matthis Kohli
Matthis Kohli

Reputation: 1995

Combining the following from ivanvanderbyl.

COPY entrypoint.sh /entrypoint
RUN chmod +x /entrypoint
ENTRYPOINT ["/entrypoint", "node", "--harmony-async-await"]

And the official documentation on ENTRYPOINT, Run multiple services in a container and reading through a bunch of Bash tutorials I came up with the following solution.

#!/bin/bash
echo " # Starting Scraper"
node index.js -D
status=$?
if [ $status -ne 0 ]; then
  echo "Failed to start node: $status"
  exit $status
fi
echo " # Init Restart-Routine. Beware, console will freeze!"
while :
do
  echo "[1]/[4] Sleep"
  sleep 5
  echo "[2]/[4] Kill node process"
  pkill -f "node index.js"
  echo "[3]/[4] Sleep 2 seconds to make sure everything is down"
  sleep 2
  echo "[4]/[4] Start NodeJS"
  node index.js
done

The final product does the following: When I start Docker it starts my node application and after a period of time it kills the node process BUT NOT the docker process and restarts it. Exactly what I was looking for.

Upvotes: 1

Ramankingdom
Ramankingdom

Reputation: 1486

Install Node cron

$ npm install --save node-cron

Import node-cron and schedule a task: var cron = require('node-cron');

cron.schedule('* * * * *', function(){
  console.log('running a task every minute');
});

Upvotes: 1

Related Questions