8 Heroku Add-ons for Production Ready PHP Apps

This article was sponsored by Heroku, the cloud application platform. Thank you for supporting the sponsors that make SitePoint possible!

Introduction

Heroku is a cloud application platform that makes it super easy to deploy and maintain apps. They take care of app management and scaling, and you as the developer can focus on more important and instantly gratifying things.

Your apps are distributed as releases, which in turn contain a slug, configuration, and add-ons. Every time you install a new add-on, change your source code, or change configuration, a new release is generated, and Heroku persists all previous releases so you can roll back to a previous version of your app very easily should something go wrong.

Slugs contain compiled units of code, the language runtime required, fetched dependencies, and everything else needed to run your app. Slugs are generated using buildpacks – sets of open source code that describe how a slug is to be generated. Here’s an example of a PHP buildpack.

Heroku uses “dynos” as units of computing power which spin up your slugs. Dynos are lightweight, isolated containers for your apps which can execute any process type and can run and scale independently. There are two types of dyno – a web dyno, which handles web requests letting you serve more users as you increase your web dyno power, and worker dynos, which handle everything else like running your code and processing background tasks.

You start with a free account, then pay for additional dyno use and scale up easily as needed – no complicated migration procedures to prepare for that extra spike in traffic you’re feeling for the weekend. Furthermore, as you push new versions of your application, slugs are regenerated completely, new dynos are spun up to run them, and a new release is generated. You’re allowed 750 free dyno hours per month, and with a single web dyno spinning 24 hours a day for 31 days, you get to 744 – leaving you 6 extra hours for toying around with scaling up and down, testing load distribution and so on.

Like any new technology, it takes a while to get used to. In particular, Heroku is very app-centric. There’s no software but your application. Deploy a few apps, and follow their tutorials to get a feel for it. Once you set up an account, you can start deploying. For a neat breakdown on how Heroku works, see this post.

Demo App

As a demonstration, we’ll be using a sample application with Laravel and deploying it on Heroku. To follow along, please do the following:

  • read about and download the Laravel Homestead. Make sure it all works before proceeding.
  • add a new site to the sites block in Homestead.yaml:
sites:
    - map: homestead.app
      to: /home/vagrant/Code/Laravel/public
    - map: heroku.app
      to: /home/vagrant/Code/heroku/public
  • run vagrant provision to install this new site, and add the heroku.app alias to your hosts file with 127.0.0.1 heroku.app
  • create a folder heroku with the subfolder public in the root of your homestead folder, and inside, put the file index.php with the content:
<?php
echo "Hello Laravel";

This is just to make sure everything works. Try visiting http://heroku.app:8000/ in your browser, and see if you get this:

With that, our local development environment has been set up. Let’s configure this thing for Heroku now.

Exit the VM and destroy it with vagrant destroy.

Prepare for Heroku

By default, Foreman (the tools Heroku uses to run a local environment) serves the site you’re running on port 5000. You can change this with the -p flag, but the regular port 80 is then taken by another runaway nginx worker, so let’s avoid complications and open port 5000.

Edit the file scripts/homestead.rb in your Homestead’s main folder (on your host machine), and add the necessary line to the port forward block:

    # Configure Port Forwarding To The Box
    config.vm.network "forwarded_port", guest: 80, host: 8000
    config.vm.network "forwarded_port", guest: 5000, host: 5000
    config.vm.network "forwarded_port", guest: 3306, host: 33060
    config.vm.network "forwarded_port", guest: 5432, host: 54320

Then, run vagrant up to boot up the VM, and SSH inside it with vagrant ssh.

  • install the Heroku toolbelt by running the following command in the terminal of your VM, while SSHed into it:
wget -qO- https://toolbelt.heroku.com/install-ubuntu.sh | sh

  • check if heroku has been properly installed by executing either heroku --version or heroku login to log into your account. You need a Heroku account for this, so if you don’t have one, sign up for free. During authentication, you may or may not be asked to generate/upload an SSH key. If you’re asked to do so, do it for easier future authentication.
  • while still in the VM, check if Composer is installed by running composer. If it is, update it to the latest version by running sudo composer self-update. If it isn’t, install Composer globally.
  • create a symbolic link like so: sudo ln -s /usr/sbin/php5-fpm /usr/sbin/php-fpm. This is so Heroku’s Foreman tool can launch FPM when you run foreman start.
  • stop nginx and php-fpm by running the following two commands:

    sudo service nginx stop
    sudo service php5-fpm stop

    We do this to free up port 80, which is occupied by nginx by default, so that Foreman (Heroku’s tool) can take over when we use it to launch nginx+php and our app.

Get the app

Now that we have the local Heroku platform prepared, we can grab an app to use with it.

  • remove the entire Code/heroku folder to make room for our new app. Make sure you’re in the Code folder now.
  • git clone https://github.com/sitepoint-examples/laroku heroku
  • cd heroku
  • composer install
  • sudo foreman start

This started nginx and php-fpm via Foreman. Due to a bug, we need to do some more actions before the app is runnable. Open another shell tab/window and enter the VM via SSH. Don’t close or stop the current shell instance which is still running Foreman.

In the new shell, run sudo chmod 777 /tmp/heroku.*

This will make the heroku files in the tmp folder world-writable, letting the nginx that Foreman is running use the socket file placed in /tmp. That’s it. If you visit http://heroku.app:5000/ on your host machine now, you should see:

Congratulations, you now have a PHP app running on a local Heroku instance, maintaining full parity between production and development! What’s more, it’s running on Homestead, the “guaranteed-to-work” Vagrant-powered VM!

It’s a bit convoluted to get up and running for now, but PHP on Heroku is still a beta feature and everything is still to be simplified. When that happens, this article will be updated accordingly.

Deploying the app on Heroku

Let’s see if the basic demo app works online now, too.

In your app’s folder (inside Code/heroku) run heroku create. This created a new remote on the Git repo called heroku. To deploy our app live, all we need to do is git push heroku master, or, in other words, push the master branch to the Heroku remote. When pushed, Heroku automatically detects it’s dealing with a PHP app, builds everything we’ve done locally, and launches our app’s newest version on a generated URL. In my case, the URL was http://safe-caverns-6867.herokuapp.com/.

Note: running heroku open from the VM to launch your app won’t work, because the VM has no browser command, nor a GUI. You need to manually launch it from the host.

Add-ons Marketplace

While it’s, obviously, dead easy to deploy your application on Heroku, it’s even easier to spice it up with some nifty plugins and add-ons for your dynos from the Add-ons Marketplace. Like we stated before, add-ons are a key part of an app’s release alongside the slug and the configuration. An add-on is, for example, the Heroku Postgres, a database layer for your application which various dynos can use for persisting consumer data or even communication between one another (dynos don’t persist file system changes – what you push to Heroku with Git is what’s contained in the slug once it’s generated – nothing more).

With so many add-ons, it’s worthwhile browsing the catalog to understand which services are available to immediately provision and extend your application with. Lucky for you, we’ve compiled a list of the most essential ones you shouldn’t miss out on in order to make your app production ready. Note that we’ll avoid application specific add-ons like databases or SMS services and the like. Instead, this list will cover the add-ons you should use to bulletproof your app and make it secure, fast and reliable.

Note also that the add-ons are listed in no particular order of importance, and that the list excludes those only available in the US regions – we look exclusively at US + EU region add-ons.

Verifying

In order to install the add-ons we’ll be mentioning below, you need to verify your accounts. You do this only once per account, not once per app. Verification is done by inputting credit card information into the Heroku account page, even if you’re not purchasing anything.

Go to heroku.com/verify to do this if you want to test any of the add-ons below. You can easily remove the payment information later on.

1. Papertrail (logging)

Papertrail is a cloud hosted log management app designed to accept, save and analyze your app’s logs out of Heroku’s log output stream (Logplex), so you can come back to it later and see what went wrong, when and why. PT groups similar errors, allows you to search the error stack with insane precision, and helps you detect trends in failures.

The free Heroku plan is 10MB per day, which is three times the volume Papertrail offers on its own. On the free plan, your logs are indexed and realtime searchable for two days, while the archive of the logs lasts for a week. The very first paid plan already boosts this to a year’s worth of archive, and a search duration of a week, which should be more than enough to detect and find that elusive error.

Any production ready app should have decent error handling included, and Papertrail fits the bill – it made cloud error management pleasant, and removed a huge developer obstacle in tracking down bugs and getting your app up to speed again. Installing the add-on is as simple as executing heroku addons:add papertrail in your app’s folder. Let’s do that now.

Execute heroku addons:add papertrail.

The easiest way to see the logs is by going into the Heroku dashboard and selecting Papertrail there. Do a couple of refreshes on your app and notice the logs filling up:

Simple! You can now search them, archive them, delete them, and more.

2.

Stillalive and Ranger are status monitoring applications that let you know if your application dies. If your business is riding on an application, you’re naturally going to want to know when it’s experiencing hiccups, be it the middle of the night or a serious stakeholder meeting. Not reacting fast means bleeding users, and bleeding users means bleeding money for most startups that care about success more than being acquired.

The Stillalive add-on here looks to be the better choice than the Ranger add-on at first glance, due to the fact that StillAlive also checks your signup procedure and your e-commerce to alert you of possible mission critical failures even if the rest of your app is up, but Ranger is cheaper initially and supports 5 URLs out of the box on the cheapest plan.

Whichever you choose, don’t let your app go live without a status checker of this type – being production ready means being disaster ready too. Installation procedures are on their respective add-on pages. We won’t be installing them in this case, as neither offers a free tier.

3. New Relic

New Relic, the company we all know by now as the pinnacle of website analytics and diagnostics, offers its services as a Heroku add-on as well. New Relic likely needs no introduction – and if it does, there’s a good tutorial covering it on our Ruby channel. In short, it measures front end performance, back end performance, customer satisfaction, bottlenecks in databases and much more, and the add-on on Heroku offers two interesting plans for free – one with a limited number of dynos, but offering a full array of New Relic services, and one giving you analytics across an unlimited number of dynos, but cutting down on some of the more serious stats.

When picking a guardian angel for your app, you can’t go wrong with a behemoth like this one. Make sure your app stays production ready by bulletproofing it with the New Relic add-on. Installing is as simple as heroku addons:add newrelic. Currently, PHP support is not yet official, but is coming soon.

4. + 5.

To make sure your app can withstand the unpredictable bouts of high traffic caused by an inexplicably active Reddit or HN thread, there’s Loader – a service that can bomb your application with requests so you can see a real use case of a request flood bringing it down and prepare accordingly. In tandem with New Relic for performance and Papertrail for error tracking, you can optimize your application for massive waves of traffic in a matter of hours, targeting the exact areas that are most problematic, instead of blindly following best practices others told you about. The add-on can be installed by running heroku addons:add loaderio. Do this now, then access the add-on’s functionality via the dashboard.

Loader requires you to verify ownership of your page first, so that you don’t use it to bomb someone else’s site. This is done via a TXT record in the DNS of the domain you’ve bound to the app (not possible for us, as we’re only using the auto-generated Heroku domain), or by adding a bit of code to your app. Go to “New Test” in the Loader dashboard, fill in the desired information, and proceed to the verification page. URL verification expects to find a very specific string on a very specific URL. Luckily, we have Laravel’s router at hand. Open routes.php in your IDE and under the line Route::get('/', 'HomeController@showWelcome'); add:

Route::get('/loaderio-xxxxxxxxxxxxxxxxxxxxxxxxxxx',function(){
    return 'loaderio-xxxxxxxxxxxxxxxxxxxxxxxxxxx';
});

Replace loaderio-xxxxxxxxxxxxxxxxxxxxxxxxxxx with your own verification key, of course. Commit and push these changes to the heroku remote to rebuild the app with the new route.

git commit -am 'Added new route for Loaderio'
git push heroku master

As soon as your app rebuilds and launches, click “Verify and start test now”, and watch loader attack your application:

After bombarding your application, looking at the results, and preparing it for high traffic, you can utilize CloudVertical. The add-on, which can be installed with heroku addons:add cloudvertical is still in beta and thus only offers a free test plan, but its focus is analyzing the usage of your dynos and predicting your cloud hosting costs. CloudVertical will let you know of the big spenders, and you can use all the add-ons mentioned before it to focus on optimizing the most expensive bits – from databases that have too slow queries and could use a boost with a proper search engine on top, to back end processes which could be optimized with message queue delegation.

Let’s install it with heroku addons:add cloudvertical.

Access it through your dashboard, input the API key when it asks for it, and you’re set! It instantly begins the analysis of your dyno hours.

As you can see, it’s empty right now. There’s not much you can do with it at such short periods or on a single dyno, but leave it installed at running (it’s free) and it’s guaranteed to produce some useful insight eventually.

Making sure your application stays production-ready is more than just keeping it alive – it’s keeping it affordable and durable. Use these plugins to optimize for traffic spikes and to remove cost spikes.

6. Fastly

A good CDN is worth its weight in gold and can shave off a decent bit of your dyno time, so let’s have a look at the Fastly add-on, which can lighten the load on both your application and your wallet.

This add-on can be installed by running heroku addons:add fastly. Find more information on Fastly on the add-on page.

7. Deploy Hooks

The Deploy Hooks add-on is a simple one, but comes in incredibly handy for us OCD types when working in teams. The premise is simple – deploy hooks let you ping an endpoint (be it an email address, Hipchat, a URL, Basecamp, etc) whenever your application is redeployed. An application is redeployed as soon as a new push is made to the heroku remote, so this add-on serves one precise purpose – letting you know when one of your developers made some changes. StillAlive reporting a dead site after Dave’s push triggered a hook alert? Time to call Dave.

When installing this add-on, you need to add extra parameters in order to configure it for where to send the messages. I chose email, but you can see how the rest is configured here. Do the following:

heroku addons:add deployhooks:email \
> --recipient=bruno.skvorc@sitepoint.com \
> --subject="Caverns deployed!" \
> --body="{{user}} deployed Caverns!"

Now make a change in your application, add, commit, and push to the heroku remote to see it in action (after you change the email address to yours, of course).

8. IronMQ

IronMQ was covered before on SitePoint, just see the IronMQ tag. It’s a message queue service that handles background processes and helps you delegate computationally heavy tasks or those that are simply slower than the usual to background processes which grab them when they can. In an effort to keep your application production-ready and running, a message queue is almost essential these days – be it sending email notifications in the background, processing user uploaded media, or doing analytics for later – you can’t go wrong with an IronMQ free plan.

Install the add-on by running heroku addons:add iron_mq and read up on our implementation series to get it up and running fast.


With this list of add-ons, your application will turn from a hobby or development project into an unstoppable behemoth, worthy of the modern web. Yes, running them all on tiers above free will set you back somewhat, but as the saying goes – if you think it’s expensive to hire a professional, wait ‘til you hire an amateur. The minor offset in money now will, provided your idea is any good, net you enormous savings down the line – and the decoupled nature of every part of a Heroku app only helps in the matter.

Conclusion

Whether your application is big or small, Heroku is one of the most convenient ways to deploy and manage it. Instead of wasting time on server management and meta setups with library juggling and VPS sorcery, you can instantly get knee deep in code and start hacking away at your next big idea.

Heroku’s Add-ons marketplace offers a plethora of essential add-ons, often in direct competition with one another, so you can be certain there’s a flavor available for everyone – just scroll through the list, activate the plugin for your app, and enjoy a vastly improved environment.

Got any favorite add-ons? Any peculiar use cases you’d like to share? Let us know!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • MadisonDouglas

    my best friend’s mother-in-law makes $73 an hour on the laptop . She has been fired from work for 9 months but last month her paycheck was $16734 just working on the laptop for a few hours, chek out the page.
    ====>>>>http://www.job-wiki.com/

  • BennyBrown

    Google is paying 80$>>CLICK NEXT TAB FOR MORE INFO AND HELP

  • KerryJTruong

    Google is paying 80$ per hour! Work for few hoursand have more time with friends & family! On tuesday I got a great new Land Rover Range Rover>>CLICK NEXT TAB FOR MORE INFO AND HELP</b

  • ProWebSoftware

    How do you get around the bug sudo chmod 777 /tmp/heroku.* when deploying to Heroku? It is ok to ‘vagrant ssh’ locally to fix it, but when deploying to Heroku how do you run this command automatically? I have followed the instructions and got this to deploy to Heroku with the custom build pack and now this bug is holding me back. Also, as of yet, I have not managed to see any php errors in the Heroku logs (using PaperTrail)