Tải bản đầy đủ (.pdf) (100 trang)

Heroky up and running

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.61 MB, 100 trang )

Free ebooks ==> www.ebook777.com

www.ebook777.com


Free ebooks ==> www.ebook777.com


Free ebooks ==> www.ebook777.com

Heroku: Up and Running

Neil Middleton and Richard Schneeman

www.ebook777.com


Free ebooks ==> www.ebook777.com
Heroku: Up and Running
by Neil Middleton and Richard Schneeman
Copyright © 2014 Neil Middleton and Richard Schneeman. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (). For more information, contact our corporate/
institutional sales department: 800-998-9938 or

Editors: Mike Loukides and Rachel Roumeliotis
Production Editor: Kara Ebrahim
Copyeditor: Jasmine Kwityn
Proofreader: Becca Freed


November 2013:

Cover Designer: Randy Comer
Interior Designer: David Futato
Illustrator: Rebecca Demarest

First Edition

Revision History for the First Edition:
2013-11-06: First release
See for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc. Heroku: Up and Running, the image of a Japanese Waxwing, and related trade dress are trade‐
marks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐
mark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.

ISBN: 978-1-449-34139-8
[LSI]


Free ebooks ==> www.ebook777.com

Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

1. Getting Started with Heroku. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
The Dawn of Virtual Servers
Enter the Cloud
You New Around Here?
Quick Start

1
2
2
3

2. How Heroku Works. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
What Is a Dyno?
HTTP Routing
Request Life Cycle
Long-Running Requests
The Dyno Manager and Dynos
Configuration
Releases
Slug Compilation
Scale Out, Not Up
Erosion Resistance
Workers and Background Processing
Other Services
The Logplex
Databases and Other Add-Ons
Deployment Systems

7
8

9
9
9
11
12
12
13
14
15
16
16
17
18

3. Understanding Performance and Scale. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Horizontal Scaling and You
Stateless Architecture
Dyno Manifold

21
22
23

iii

www.ebook777.com


Free ebooks ==> www.ebook777.com
Autoscaling

Estimating Resource Requirements
Request Queuing
Speeding Up Your App
Expires Headers
Faster Page Response with a CDN
Postgres Database Performance
Explaining Postgres Performance
Caching Expensive Queries
Back that Task Up
Full-Text Search Apps
Performance Testing
In-App Performance Analysis
External Performance Tools: Backend
External Performance Tools: Frontend
Being Fast

24
24
25
25
26
26
27
28
29
29
30
31
31
31

32
32

4. Heroku Regions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Multiregion or Single?
The Heroku Way
How to Deploy in a New Region
Forking an Application
Constraints
Latency
Add-Ons

34
34
34
35
36
36
37

5. Heroku PostgreSQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Why PostgreSQL?
Transactional DDL
Concurrent Indexes
Extensibility
Partial Indexing
What Heroku Gives You
Development versus Production
Choosing the Right Plan
Shared Features

Starter Features
Production Features
Getting Started
Importing and Exporting Data
Importing Data
Exporting Data

iv

|

Table of Contents

39
40
40
40
41
41
41
42
43
43
44
44
45
45
46



Free ebooks ==> www.ebook777.com
Snapshots
CSV Exports
PGBackups
Data Clips
Followers
Fast Database Changeovers
Forking
Other Features
Extension Support
Improved Visibility
JSON Support
Range Type Support

47
47
47
48
48
49
50
51
51
52
53
53

6. Deployment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Timeliness
Backing Out

Testing
How to Deploy, and Deploy Well
Backups
Heroku Releases
Performance Testing
Trimming the Fat (Slug Management)
Source Code Management
Multienvironment Deployment
Teams
DNS
Configuration

55
55
56
56
56
57
58
58
59
60
62
62
63

7. When It Goes Wrong. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Dev Center
Heroku Support
Deploy Debugging

Heroku Status Site
Reproducing the Problem
Check for a .slugignore File
Fork and Use a Custom Buildpack
Deploy Taking Too Long?
Runtime Error Detection and Debugging
Deploy Visibility
Test Visibility
Performance Visibility
Exception Visibility

65
65
65
66
66
67
67
68
69
69
70
70
71

Table of Contents

www.ebook777.com

|


v


Free ebooks ==> www.ebook777.com
Logging Add-Ons
Exception Notification
Uptime Visibility
Twitter-Driven Development
Code Reviews and a Branching Workflow
Runtime Error Debugging
Data State Debugging
Asset Debugging
Application State Debugging

71
72
73
73
74
74
74
75
75

8. Buildpacks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Before Buildpacks
Introducing the Buildpack
Detect
Compile

Release
Profile.d Scripts
Leveraging Multiple Buildpacks
Quick and Dirty Binaries in Your App
The Buildpack Recap

vi

|

Table of Contents

77
78
78
79
80
81
81
83
83


Free ebooks ==> www.ebook777.com

Preface

So, What Is Heroku?
If you’re old enough and lucky enough to have had access to a computer in the early
1990s, you may have experienced the joy and wonder that was an MS-DOS game. These

games were marvels of their time, but a number of them required you to do something
odd, which was reboot your computer and boot into the game itself, thus taking the
operating system (OS) out of the equation while the game was running.
The reason was that the OS put constraints on the game program; it used up resources
needed by the game and forced certain rules into place that weren’t necessarily helpful
for the game to run efficiently.
As time moved on, this approach was no longer needed. Operating systems were be‐
coming more advanced and games were able to run quite happily within their bound‐
aries. The games were able to benefit from the additional help that the OS gave for
interfacing with hardware and so on.
These days, we would never imagine running our games outside of the platform pro‐
vided by the OS; it’s just too much work and involvement for the developer. Why would
a developer rewrite a whole hardware interface or library of sound drivers when it can
rely on those provided by the OS?
Now think about this in the context of the Web. In the early days of deployment, ev‐
erything was very much a homegrown affair: developers and system administrators had
to figure out a lot of how things bolted together themselves, and worry about the things
they had missed. As time rolled on, more and more tools and software became available,
which made their lives significantly easier.
These days, though, we have platforms such as Heroku, which you could almost consider
to be one of the Web’s operating systems. As a developer, you can write your application
in the way a game designer would—you don’t need to worry about the details of how
your database server is set up and you don’t need to worry about how your servers are
vii

www.ebook777.com


Free ebooks ==> www.ebook777.com
kept up to date. Heroku is a platform that takes care of all of these things and allows you

to integrate with it how you will.
Now, we are in a position where the idea of a developer building a server to host an
application is becoming almost a bizarre route to take. Each day, hundreds of developers
deploy applications, and fewer and fewer are getting involved in the nitty-gritty of in‐
frastructure, instead choosing to use platforms such as Heroku.

Who This Book Is For
This book is aimed at anyone who is already using Heroku in one form or another, and
wants to learn more about the best ways to make use of the technology available. This
book makes the assumption that you are already proficient in using your own language
of choice and are happy using Git for your source control needs.
The book assumes no previous knowledge of Heroku itself, but you will get more from
it if you have deployed an application or two to the platform already.
Lastly, you should not be afraid of documentation. There is a vast array of content
available, both on the subject of Heroku itself and the various languages that can be
deployed to it. Therefore, instead of repeating that content, we encourage you, the
reader, to go out and review whatever you can find on a given topic.

The History of Heroku
Heroku is still a relatively young company, having only started in 2007 (making Heroku
younger than the Apple iPhone!). Back then, the three founders—James Lindenbaum,
Adam Wiggins, and Orion Henry—were all working together at a small web develop‐
ment agency, and found that the amount of time spent deploying an application once
having built it was not proportional. For instance, they were commonly finding that an
application might take a month to develop, but then they would need to spend a week
deploying the application to the Web.
After a while, they started developing applications using Ruby on Rails. With this came
a newfound productivity, yet the time for deployment hadn’t changed. Therefore, the
three of them had the idea of bringing the same sort of efficiencies to application hosting.
In six weeks, an idea was developed and a prototype was built: a simple platform that

was easy to deploy to and straightforward for a developer to figure out.
Interestingly, the initial prototype was nothing like the Heroku you see today. For in‐
stance, one major component was an application called Heroku Garden (although it
wasn’t known by this name at the time), a web-based code editor that users could log
into and use to edit their code via a browser (see Figure P-1). Once you hit Save, the
code was deployed and running on the Web, ready for users to see. Interestingly, there

viii

|

Preface


Free ebooks ==> www.ebook777.com
are more web-based code editors popping up in 2013, which shows how far ahead of
the curve it was.

Figure P-1. Heroku Garden
Over time, however, Heroku found that more and more of its target users were interested
in the application hosting aspect of the product instead of the web-based editor. There‐
fore, Heroku developed an API that developers could use alongside Git, the source
control system. Developers could also use the API to push their code to the Heroku
platform.
Use of this API grew, and Heroku took the decision to turn off Heroku Garden com‐
pletely. In January 2009, Heroku relaunched and rebranded itself as a Ruby/Rack de‐
ployment platform, and interest in and adoption of the product grew significantly.
Heroku is constantly developing the stack that is available for use, starting with the
Aspen and Bamboo stacks, and moving to the current Cedar stack, which this book
talks about.

Cedar is a big move forward in that it allows Heroku to become a fully polyglot platform
(i.e., it can run many different types of applications within the same stack). Ruby is no
longer the only option for use on Heroku, with the platform now supporting Python,
Preface

www.ebook777.com

|

ix


Free ebooks ==> www.ebook777.com
Java, Node.js, Clojure, and Scala, and providing the potential for a vast amount more
via the use of Heroku buildpacks, which we will talk about more later in the book.

The Heroku Culture
It’s probably worth mentioning the Heroku culture and how this affects its approach to
software and how things are put together.
Picture the movie industry just 70 years ago. If you wanted to watch a film, it had to be
what was playing at the local cinema. Hundreds of people would congregate and watch
that film together, and it would be fun.
By the 1980s, the magical idea of the videocassette was taking off. Now people could
choose what film to watch and when, assuming that they had access to the media. The
technology was much smaller, and the media much more readily available.
Come the 1990s, the DVD made its entrance. Again, smaller devices, smaller media,
but with another iteration in quality and capability. Over the matter of a couple of
iterations, we had gone from a massive cinema to a box no bigger than a large book.
And these days, we’ve advanced yet another step. We can now stream any film we like,
whenever we want, regardless of whether we own it or not. What’s more, we don’t need

any specific hardware or media in the house. We just need a device connected to the
Web.
But why are we talking about this? Well, this history matches the ethos at work within
Heroku. Heroku strives to turn the age-old and complex process of hosting an appli‐
cation on the Web into one that requires no hardware and no software—you push your
code up and the job is done. Heroku is striving to create the Netflix equivalent of ap‐
plication provisioning. In the world of Heroku, if there’s a choice between software or
service, service wins every time.

Why Would I Want to Learn More About Heroku?
By knowing more about the inner workings of the Heroku stack, you’ll be able to make
better educated guesses about how to architect your applications so they can work as
efficiently as possible. You’ll be able to identify where you need to focus your own efforts
when developing your code, and which parts of your code can be left to add-ons and
so on that might be available to you. You’ll be able to recover an application should it
go down because you will know where and what to look for. What’s more, you’ll un‐
derstand the benefits that the platform can give you and how to encourage those around
you to use the platform.

x

|

Preface


Free ebooks ==> www.ebook777.com

Conventions Used in This Book
The following typographical conventions are used in this book:

Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width

Used for program listings, as well as within paragraphs to refer to program elements
such as variable or function names, databases, data types, environment variables,
statements, and keywords.
Constant width bold

Shows commands or other text that should be typed literally by the user.
Constant width italic

Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.
This icon signifies a tip, suggestion, or general note.

This icon indicates a warning or caution.

Safari® Books Online
Safari Books Online is an on-demand digital library that delivers
expert content in both book and video form from the world’s lead‐
ing authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research, prob‐
lem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi‐
zations, government agencies, and individuals. Subscribers have access to thousands of
books, training videos, and prepublication manuscripts in one fully searchable database
from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐
fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John

Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT
Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course

Preface

www.ebook777.com

|

xi


Free ebooks ==> www.ebook777.com
Technology, and dozens more. For more information about Safari Books Online, please
visit us online.

How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at />To comment or ask technical questions about this book, send email to bookques

For more information about our books, courses, conferences, and news, see our website
at .
Find us on Facebook: />Follow us on Twitter: />Watch us on YouTube: />

From the Authors: Neil Middleton
I started to get involved with Heroku back in 2009 when the development shop I was
working at was looking for a simple, effective, and relatively cheap platform for hosting
our Ruby on Rails applications. After trying a few different options, we were looking at
using a virtual private server (VPS) or Heroku. A few days later, we knew Heroku was
the way to go. We could get applications running with the least amount of hassle in the
least amount of time, and what’s more, only pay for what we needed when we
needed it.
As time went on, my relationship with Heroku grew closer as I got more and more
involved in the platform and I started to base my website articles on best practices and
know-how surrounding the product.
Eventually, a couple of things happened. First, I was approached by Heroku and O’Reilly
to put this book together with Richard, and second, I ended up working at Heroku full
time as part of the support team. The last year, therefore, has been a pretty dramatic

xii

|

Preface


Free ebooks ==> www.ebook777.com
one, and one that I feel will open up some new horizons—some that will improve cus‐
tomer knowledge of the platform, but also to help Heroku confirm that step into the
big league of application hosting.

From the Authors: Richard Schneeman
I remember vividly the first time I heard about Heroku: I had just struggled over the
course of seven painful days to deploy my first Rails app to a shared hosting provider.

I was running Rails 1.2 then. I looked at Heroku, saw it was free to try, and gave it a shot.
I was blown away. It took a few minutes to do what took days on another provider—I
was addicted. It wasn’t entirely love at first deploy though; I tried several other platforms,
all of which are now out of business, to see how they fared. I actually ended up using
one called mor.ph for a few months because it allowed me to do things that Heroku
wouldn’t. Eventually, I moved on to my own VPS with a respected cloud provider. I was
running a half-dozen sites on one VPS and used another dedicated VPS running a mail
server to receive incoming mail for an email anonymizing service I used to run called
whyspam.me.
Life was good. Or at least it was until the first of many times my sites went down. I was
at work, and couldn’t SSH into my box to diagnose until I got home. The fix was simple,
but the message was clear: if I was going to run anything serious, I needed to get some
more firepower. I switched back to using Heroku and found that those things I couldn’t
do once, I had no desire to do anymore. They were the same things that caused my VPS
to be unstable, so I ended up rewriting those features anyway. What once seemed like
arbitrary limitations were now revealed as well-seasoned advice from an opinionated
platform.
This was about the same time I began to teach Rails at the University of Texas, and I
needed the easiest way for my students to deploy: I chose Heroku. After the lecture on
deployment, one of my students actually asked me why programming Rails couldn’t be
as easy as deploying it. I believe my reply started off “back in my day…”—if only they
knew.
In the meantime, I began working full time for a social network called Gowalla. I loved
working on it like only a crazed programmer bent to change the world can love some‐
thing. When Gowalla was purchased by Facebook in 2011, I sent a note out to my favorite
Ruby-backed companies. Luckily for me, Heroku—my number one choice—decided to
write back, and I’ve been working there ever since.
I love working on Heroku, and I love introducing people to the beauty on the surface
and under the covers of the platform. When the opportunity to write a few words about
Heroku came up, I jumped on the chance, and here I am now.


Preface

www.ebook777.com

|

xiii


Free ebooks ==> www.ebook777.com

Disclaimer
These days, things are moving fast, and especially so in technology. In fact, almost every
day we are seeing changes being made to the Heroku platform. Most of these changes
are invisible to the user, but changes nonetheless.
In the print world, however, things are set in stone (or ink). Therefore, there are likely
to be some inaccuracies or apparent mistakes due to these potential changes. If in doubt,
check out the Heroku DevCenter for the authoritative source of up-to-date
documentation.

xiv

| Preface


Free ebooks ==> www.ebook777.com

CHAPTER 1


Getting Started with Heroku

All day, every day, the Internet gets larger and larger, and recent estimates show simply
phenomenal growth. Every minute, the Web is growing at a rate of over 500 new sites,
while popular video hosting service YouTube is said to be receiving over 48 hours of
new video content. Twitter users create over 100,000 new tweets, while Facebook users
share over 600,000 new posts.
To the common observer, these numbers are amazing. However, to the developer, these
numbers are simply incredible, not only because of the sheer size of the applications
required to support this growth, but also the infrastructure in the form of servers and
bandwidth required to keep these services ticking over happily 24/7.

The Dawn of Virtual Servers
No more than 10 years ago, the way a developer such as yourself would bring a new
website or application onto the Web was to go out and purchase a new server, configure
it, and find a data center that would host the server in a rack for you. This data center
would provide your server with the life support that it needed to carry out its task:
bandwidth, power, cooling, and the list goes on. Only once you had all these items lined
up would users on the Web be able to type in your URL and find themselves looking at
your website.
Now fast-forward a few years. Developers increasingly have the option of virtualization.
Virtualization is the practice of renting a “virtual” server from a third party (be it another
company or an internal IT team) and using that in place of your own physical machine.
A virtual server would appear to the outside world to be just like a regular physical
server; however, it only exists with the processes of a parent server, sharing resources
and saving costs.
As a physical server is able to contain multiple virtual servers, an industry sprung up
where companies would create data centers filled with machines that were sliced up and
1


www.ebook777.com


Free ebooks ==> www.ebook777.com
rented out to developers to use for their applications. This brought great gains for the
developer: there was no longer a need to tie up capital in purchasing a physical server;
there was no need to worry about maintaining the machine if things went wrong; and
what’s more, it was available within hours rather than the days that it would have taken
to procure and install a physical server.

Enter the Cloud
The first decade of this century brought the concept of cloud computing. As demand
for hosting grew and grew, and applications became larger and larger, a new form of
hosting became apparent: cloud computing. Pioneered at a massive scale by Amazon’s
Elastic Compute Cloud (EC2), cloud computing allowed developers to “spin up” virtual
instances of servers on the Web and interact with them in the same way as normal
machines. The key difference between these servers and traditional virtualization is that
they are generally billed on a usage basis (usually by the hour), and at no point does the
developer have any real idea of where the server is physically.
Cloud computing vendors such as Amazon do not rent out virtual servers; rather, they
rent out a certain amount of computing capacity. It is up to the vendor where this
capacity is provided from, and it is up to the vendor to provide and manage all the
ancillary services that surround it.
Because the vendor is in complete control of the capacity and the ancillary services, new
possibilities are available. For instance, suppose your website is mentioned on the
Hacker News home page and you have 10 times the normal amount of traffic visiting
your site. In the good old days of physical servers, your site would go down under the
load and you’d be powerless to stop it, as you would be reliant on being able to purchase
new hardware and configuring and installing it in your data center. With virtualization,
you’d be better off: you’d be able to buy more servers from your vendor and have them

up and running within a couple of hours, but until then your site would be down. With
modern cloud-based hosts, you’d simply add more capacity to your application and
instantly scale to meet the demand. What’s more, you wouldn’t be locked into this larger
infrastructure, as you would with the other options—you simply scale up or down as
necessary and only pay for the resources you have used.

You New Around Here?
Never used Heroku before? Jump on over to and give it a spin.
We won’t duplicate all of the site’s getting started material. Instead, we’ll focus on giving
you in-depth insight into how Heroku works and how to get the most out of the platform.
If you’ve deployed to or shared VPS servers, there are some differences (which we’ll
cover later), but here is a quick list to check out before getting started:

2

|

Chapter 1: Getting Started with Heroku


Free ebooks ==> www.ebook777.com
Ephemeral file system
You can write to and read from disk, but as soon as your server restarts—and it will
—that’s all gone. Instead, use a shared file-storage system such as Amazon Simple
Storage Service (Amazon S3). This also makes running on multiple machines easier.
Shared state
If you want to store session data on your server, you’ll need to find a way to persist
it across multiple machines if you want to scale out. To do this, you can use secure
cookies and a distributed store such as Memcached.
Dependency management

If you want to install external code libraries for your app, you’ll need to do it using
a dependency management tool like Bundler for Ruby or Ivy for Java.
Scale out, not up
Heroku currently offers only one server size (called a dyno); if you need more
horsepower, use more dynos. If one dyno isn’t big enough to get your app to run,
you should consider splitting your app into smaller services, all talking over HTTP.
It works for companies like Google, Facebook, and even Heroku—maybe it can
work for you.
Logs
Once you get your app on Heroku, you might need to debug your application code
by looking at the logs. Because Heroku is different from a VPS or a shared host, you
can’t SSH or FTP into your box to see your logs. Instead, use the Heroku command
line interface to run the following:
$ heroku logs --tail

This saves you from having to SSH into multiple machines at the same time. See
“The Logplex” on page 16 for more information.
Unlike anything else you’ve probably used before, Heroku is a platform-as-a-service
(PaaS) that has plenty of opinions on how you should run your code. Although these
opinions may at first seem severe, you’ll get a flexible, scalable, fault-tolerant app that
is a pleasure to run. If you don’t want to stick to the rules, your app will not be able to
run on Heroku, and it probably won’t run well anywhere else.

Quick Start
So, at this point, if you haven’t already, it is probably worth quickly playing with Heroku
so that you can get an application up and running. By doing this, you can get a quick
overview on the deploy and build process, plus actually get an application out there on
the Web in no time at all!

Quick Start


www.ebook777.com

|

3


Free ebooks ==> www.ebook777.com
The first step, if you haven’t done this already, is to sign up for a Heroku account. Note
that nothing we are going to do here will cost you anything, so you don’t need to worry
about credit cards or charges for this exercise.
Once you’ve got an account, make sure you’ve got the Heroku Toolbelt installed. This
toolbelt will make sure that you’ve installed everything necessary for getting an appli‐
cation up and running on Heroku.
Once installed, log in via your toolbelt at the command line:
$ heroku login
Enter your Heroku credentials.
Email:
Password:
Could not find an existing public key.
Would you like to generate one? [Yn]
Generating new SSH public key.
Uploading ssh public key /Users/adam/.ssh/id_rsa.pub

For the purposes of this exercise, we’ll be deploying a sample application that we’ve
already put together, the code for which can be found on GitHub.
To get started, we need to clone this code to our local machine:
$ git clone />$ cd ruby-sample


Now that we’ve got the code, we can create an application to contain it:
$ heroku create
Creating blazing-galaxy-997... done, stack is cedar
| :blazing-galaxy-997.git
Git remote heroku added

This creates the application on Heroku ready and waiting for our code, and also attaches
a git remote to our local codebase.
Now we can deploy:
$ git push heroku master
Counting objects: 6, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (6/6), 660 bytes, done.
Total 6 (delta 0), reused 0 (delta 0)
-----> Ruby/Rack app detected
-----> Using Ruby version: ruby-2.0.0
-----> Installing dependencies using Bundler version 1.3.2
Running: bundle install --without development:test --path vendor/bundle
--binstubs vendor/bundle/bin --deployment
Fetching gem metadata from />Fetching gem metadata from />Installing rack (1.2.2)

4

|

Chapter 1: Getting Started with Heroku


Free ebooks ==> www.ebook777.com

Installing tilt (1.3)
Installing sinatra (1.1.0)
Using bundler (1.3.2)
Your bundle is complete! It was installed into ./vendor/bundle
Cleaning up the bundler cache.
-----> Discovering process types
Procfile declares types
-> web
Default types for Ruby/Rack -> console, rake
-----> Compiled slug size: 25.1MB
-----> Launching... done, v3
deployed to Heroku
To :blazing-galaxy-997.git
* [new branch]
master -> master

This has taken our code, pushed it to Heroku, identified it, and run a build process
against it, making it ready for deployment.
Now our application is live on the Internet! To verify this, open it now:
$ heroku open
Opening blazing-galaxy-997... done

Simple, huh?
Now that we’ve finished in the glory of our genius, read on to find out more about how
Heroku works in the next chapter.

Quick Start

www.ebook777.com


|

5


Free ebooks ==> www.ebook777.com


Free ebooks ==> www.ebook777.com

CHAPTER 2

How Heroku Works

At the time of writing, Heroku has had over three million separate applications deployed
on its infrastructure, and this number grows day by day. Running a large number of
applications day to day requires a substantially different approach than running just a
handful, and this is one of the reasons that the Heroku architecture is markedly different
from what you or I might develop if we were setting up our own environment on our
own hardware for a single application. Heroku’s task is to support the running of all of
these applications at the same time, managing the deployments that users are requesting,
as well as scaling applications’ needs.
In order to achieve this, the Heroku platform is broken up into several key segments;
the most important among these are:
• Routers, which ensure your application receives the requests from users on the Web
• Dynos, where your application code actually runs day to day
In addition to these, there are a number of extra components, such as the Logplex and
the various add-ons and services available to your applications (see Figure 2-1).
So, let’s walk through all of these parts in turn.


What Is a Dyno?
When you deploy an application to Heroku, it is run in a container called a dyno. The
more dynos your app has, the more running instances of your application are available
to take requests. Each dyno is completely isolated from other dynos. You can add dynos
to extend capacity and to allow for fault tolerance (since one dyno going down will not
affect other dynos). At the time of writing, each dyno represents 512 MB of physical
RAM.

7

www.ebook777.com


Free ebooks ==> www.ebook777.com

Figure 2-1. Overall architecture of the Heroku platform
Applications are billed by the dyno/hour prorated to the second, and every application
is credited with 750 dyno/hours per month. The caveat here is that Heroku idles any
applications running a single dyno when not in use to free resources for other
applications.
So, a dyno is like a small virtual computer, but if your application is split up over multiple
compute units, how does Heroku know which dynos to send requests to?

HTTP Routing
When a user types your application’s URL into a browser or tries to make a request to
it via an API (and so on), there needs to be a way to connect the user with your appli‐
cation running somewhere deep down within the Heroku platform. There are thou‐
sands of applications running on Heroku, and maintaining a persistent location for an
application within the platform is an approach fraught with danger.
The Heroku router is a piece of software (written using Erlang, called Hermes), which

acts as a gateway between your users and the dynos that are running your code. In its
memory, it is aware of every single application currently deployed to the platform and
the external URLs that each of these applications should respond to (including the
8

|

Chapter 2: How Heroku Works


Free ebooks ==> www.ebook777.com
*.herokuapp.com URLs, legacy *.heroku.com URLs, and any custom domains that you
may have added). Lastly, it stores the current location of your application on the platform
at the current time.
Therefore, the routers have a lot to keep track of. So what exactly does it look like when
a request comes in from a user on a web browser?

Request Life Cycle
When a user wants to visit your site, he types the URL into the address bar and hits
Enter. Then a DNS query is made to your provider. They see you’ve pointed your address
at Heroku either using an A record or a CNAME. With this information, the request is
sent to the Heroku routers.
Every time a router receives a request, it carries out a lookup on the URL being requested
and determines the location of your application code. Once found, it fires the request
at your code and awaits a response. This is where your application steps in and handles
the request, doing whatever you programmed it to do.
Once your code has completed processing the request and a response has been returned,
the router will pass the response back to the end user. The best part about this is that
the routers are completely transparent to the outside world.
Now that you know what happens when a request goes through, what happens if some‐

thing hangs in your application? Does Heroku just keep thousands of dead requests
alive?

Long-Running Requests
As a way of protecting the user from long-running requests, the router processing the
request will wait for only 30 seconds before returning a timeout error to the end user.
The error returned in these instances shows in your application logs as an H12. Note,
though, that this only counts the first byte returned. Once that first byte of response is
returned, the router sets a 55-second rolling window before an error is returned (in
these instances, the error code changes to an H15). This, therefore, means that you are
effectively able to stream responses back to the user without worrying about hitting this
timeout error.
Let’s say we’re sending a valid request that our server should be able to respond to. We
know that our code lives on a dyno, but where exactly does a dyno live?

The Dyno Manager and Dynos
In simple terms, a dyno is an isolated, virtualized UNIX container that provides the
environment required to run an application.

The Dyno Manager and Dynos

www.ebook777.com

|

9


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×