Mathew Antony
Mathew Antony

Reputation: 173

Automatically restarting Heroku NodeJS app

I have a NodeJS app hosted on Heroku. Is there a way for me to automatically run the "heroku restart" command every hour?

I found this answer but it looks like it's for a Rails project: Restart my heroku application automatically

Upvotes: 0

Views: 1950

Answers (2)

Jason
Jason

Reputation: 821

Using the Heroku v3 API it is possible using the request node module

var token = 'youAPIKeyHere';
var appName = 'yourAppName here';
var dynoName = 'yourDynoHere';

var request = require('request');

request.delete(
    {
        url: 'https://api.heroku.com/apps/' + appName + '/dynos/',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/vnd.heroku+json; version=3',
            'Authorization': 'Bearer ' + token
        }
    },
    function(error, response, body) {
        // Do stuff
    }
);

There is also a node wrapper that provides a similar experience, but is poorly documented and requires an understanding of the v3 API anyway

var token = 'youAPIKeyHere';
var appName = 'yourAppName here';
var dynoName = 'yourDynoHere';

var Heroku = require('heroku-client');

var heroku = new Heroku({ token: token });
    heroku .delete('/apps/' + appName + '/dynos/' + dynoName)
           .then( x => console.log(x) );

I also found it useful to experiment in browser with this code

var token = 'youAPIKeyHere';
var appName = 'yourAppName here';
var dynoName = 'yourDynoHere';

var xhr = new XMLHttpRequest();
    xhr.open(
        'DELETE',
        'https://api.heroku.com/apps/' + appName + '/dynos/' + dynoName
    );
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('Accept', 'application/vnd.heroku+json; version=3');
    xhr.setRequestHeader('Authorization', 'Bearer ' + token);
    xhr.onload = function() {
        console.log(xhr.response);
    };
    xhr.send();

  • I personally did find using the delete method a bit concerning. Caution should be taken with using the delete method and the /apps/$$appName$$ endpoint alone will delete the app. This is from personal experience

  • For any of the above, if you omit the dyno name, you will restart all dynos under the app

  • The other question references a repo that is no longer supported

Upvotes: 1

Andrew
Andrew

Reputation: 1289

Yup, use the Heroku SDK for Node.js.

Something like:

heroku.apps('my-app').dynos().restartAll()

Should do the trick. All of the dyno documentation can be found here: https://github.com/heroku/node-heroku-client/blob/master/docs/dyno.md. You can run a scheduled script using the Heroku scheduler.

I must warn you though, this is most certainly not the best way to do whatever you are trying to do. If you provide more insight into your problem I'm sure we can suggest something more appropriate than restarting your dynos all the time.

Upvotes: 1

Related Questions