Deploy Node app to Heroku

Main steps when deploying NodeJS app using Heroku CLI tool.

Based on Getting started with NodeJs.

All together:

heroku login
heroku create
heroku apps:rename cool-app
heroku config:set variable=value
git push heroku master
heroku ps:scale web=1
heroku open

To stop an app: heroku ps:stop DYNO --app <app name>

Step by step

Create git repo (I assume you are already in one).

heroku login - Logs you in from the shell

heroku create - Creates application, for example based on Connect webserver.

Note: this assumes the main file is called index.js

The command will give you a new Git remote url and will add it to the local repo.

OR if the application already exists you can add heroku remote using heroku git:remote -a <app name>

  • Use environment port (if doing web app). Instead of listening to hardcoded port, use
1
2
3
4
5
6
7
var port = process.env.PORT || 3001;
http.createServer(
ecstatic({
root: __dirname + '/public',
cache: 0
})
).listen(port);
  • Create Procfile, add web: node index.js

  • Commit node_modules/ folder to Git. I don't like this particular step, but Heroku's npm install step was often failing otherwise. Probably no longer necessary, since NPM is more robust now.

heroku apps:rename cool-app - Renames application to something meaningful.

heroku config:set DB_PASSWORD=value - Sets environment variables for application, for example

1
2
3
heroku config:set STATS_DB_USERNAME=something
Setting config vars and restarting next-update... done, v3
STATS_DB_USERNAME: something

Use environment variable from Node

1
process.env.STATS_DB_USERNAME

git push heroku master - Pushes master branch to Heroku

heroku ps:scale web=1 - Assigns 1 dyno VM to run your application

  • Check if the application started using heroku ps

  • Open application in browser heroku open

  • View logs heroku logs

Update 1

Both circleci.com and codeship.com allow automatic pushes to Heroku after the tests pass. They are much simpler to setup than managing the deploys from command line yourself.