Automatically Restarting Heroku App With Cronjob
In this blog post, I will describe how to configure an automatic restart of your Heroku app. This will be done in a few steps:
- Get a Heroku authentication token.
- Prepare the Heroku API request for restarting dynos.
- Create a script with this request.
- Add a cron job for running the created script.
Getting The Heroku Authentication Token
The Authentication Token is needed for the restart-all request. You can generate it by running:
heroku authorizations:create
using Heroku CLI.
Preparing the Heroku API Request
Heroku exposes the API to restarting all dynos. Documentation for this endpoint can be found here.
You need to make a DELETE request to https://api.heroku.com/apps/{app_id_or_name}/dynos
but remember of adding the Authorization Token in headers. Following curl
will do the job:
$ curl -n -X DELETE https://api.heroku.com/apps/$APP_ID_OR_NAME/dynos \
-H "Content-Type: application/json" \
-H "Accept: application/vnd.heroku+json; version=3"
-H "Authorization: $AUTHORIZATION_TOKEN"
where $APP_ID_OR_NAME
is your app name and $AUTORIZATION_TOKEN
is the token you generated in the previous step.
Creating the Script
Translate your curl
request into the language you are using. In my case, I used NodeJS.
import fetch from "node-fetch";
import { HEROKU_APP_ID, HEROKU_API_TOKEN } from './env.js';
console.log("Restarting dynos")
const response = await fetch(`https://api.heroku.com/apps/${HEROKU_APP_ID}/dynos`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/vnd.heroku+json; version=3',
'Authorization': `Bearer ${HEROKU_API_TOKEN}`
}
});
console.log(response)
This scripts runs the same request as described in the previous step. Commit and push changes to Heroku.
Adding the Script to the Cronjob
Firstly, add the Heroku Scheduler addon on Heroku website under your app you want to restart periodically.
Then add your job. In my case, the job runs node src/restartDynos.js
every hour.
Alternative solution
Instead of creating the script and running it with Heroku Scheduler simply run the curl from the second step directly.