顯示具有 heroku 標籤的文章。 顯示所有文章
顯示具有 heroku 標籤的文章。 顯示所有文章

2016年10月17日 星期一

如何快速使用 Heroku 来部署你的 Laravel 应用

很多 Laravel 新手在第一次做出一个属于自己的应用后,脑中都会自然而然的冒出一个想法:"我如何将 Laravel 应用部署到线上,让其它人可以通过访问一个 URL 在线上查看我的应用?"。
当你开始使用 Google 进行相关搜索的时候,你会发现有很多种解决方案摆在你面前。例如可以通过购买 Linode, DigitalOcean 服务器来部署应用,或者是使用一些如 Engine Yard Cloud 和 Heroku 这样的云部署服务来快速完成应用的部署上线。
而我今天想给大家介绍的是: 如何快速使用 Heroku 来部署 Laravel 应用?

什么是 Heroku?#

Heroku 是一个支持多种编程语言的 PaaS(Platform-as-a-Service)。在 2010 年被 Salesforce 收购。Heroku 作为最开始的云平台之一,从 2007 年 6 月起开始开发,当时它仅支持 Ruby,后来增加了对 Java、Node.js、Scala、Clojure、Python 以及 PHP 和 Perl 的支持。

为什么选用 Heroku?#

  1. Heroku 的部署上线流程异常简单。你只需要将源代码纳入到 Git 版本控制系统中即可,其它额外操作 Heroku 都会帮你自动处理好。
  2. Heroku 提供给开发者的免费套餐非常丰富。其中包括最多 5 个应用的免费创建,自定义域名的支持等。实乃良心商家。唯一的不足就是有时候在国内访问速度会比较慢。
  3. Heroku 产品服务在业内评价特别高。在 Rails 圈子中许多有经验的开发者都会使用 Heroku 来部署上线自己的 Demo 应用,其部署流程和速度都受到了 Rails 社区成员的广大好评。

Heroku 的基本安装及配置#

首先我们先 注册一个 Heroku 账号。
注册完成之后使用 Heroku Toolbelt 来安装 Heroku 客户端。
安装完毕后使用 heroku version 来检查当前系统是否已安装好 Heroku 客户端:
$ heroku version
如果有类似下面的输出,则代表 Heroku 客户端已成功安装:
heroku-toolbelt/3.43.9 (x86_64-darwin10.8.0) ruby/1.9.3
heroku-cli/5.2.39-010a227 (darwin-amd64) go1.6.2
You have no installed plugins.
安装成功之后,你需要使用以下命令来登录你的 heroku 账号:
$ heroku login
然后添加 SSH 密钥:
$ heroku keys:add
至此,Heroku 的基本安装及配置已完成。下一步我们开始尝试将应用部署到 Heroku 上。

将项目部署到 Heroku 上#

新建一个 Laravel 项目#

我们需要新建一个 Demo 项目,然后将此项目部署到线上。
$ composer create-project laravel/laravel --prefer-dist hello_laravel_heroku
$ cd hello_laravel_heroku

初始化 Git 仓库#

$ git init
$ git add .
$ git commit -m "new laravel project"

创建 Procfile#

要将应用部署到 Heroku 上,你需要新建一个 Procfile 文件,这个文件的作用是通过正确的配置来告诉 Heroku 应用应当使用什么命令来启动 Web 服务器。
将配置写入 Procfile 文件并将其纳入 Git 版本控制中:
$ echo web: vendor/bin/heroku-php-apache2 public/ > Procfile
$ git add .
$ git commit -m "Procfile for Heroku"

在 Heroku 上创建一个新应用#

我们可以使用 heroku create 命令在 Heroku 上创建一个新应用:
$ heroku create
命令行会输出类似如下信息:
Creating mighty-hamlet-1982... done, stack is cedar-14
http://mighty-hamlet-1982.herokuapp.com/ | git@heroku.com:mighty-hamlet-1982.git
Git remote heroku added
mighty-hamlet-1982 是 Heroku 随机为应用生成的默认名称,每个人生成的名称都不相同。http://mighty-hamlet-1982.herokuapp.com/ 则是应用的线上地址。
如果你对生成的默认名称不满意,你可以使用 heroku rename 来对应用名称进行更改,但要保证更改的名称未被其它人占用。如:
$ heroku rename your-app-name

声明 buildpack#

Heroku 对多种语言进行了支持,因此在应用部署的时候它会去自动检查应用的代码是用什么语言写的,然后再接着执行一系列针对该语言的操作。Laravel 的应用默认会包含 package.json 文件,但当 Heroku 检查到该文件时,它会认为此应用是用 Node.js 写的,因此我们需要对应用的 buildpack 进行声明,告诉 Heroku 我们的应用是用 PHP 写的。声明命令如下:
$ heroku buildpacks:set heroku/php

设置 APP key#

Laravel 使用 App Key 来完成对用户会话及其它信息的编码加密操作,因此我们也需要将 App Key 加入到 Heroku 的配置中。
生成 App Key:
$ php artisan key:generate
将生成的 App Key 附加到此命令行后面以完成配置:
$ heroku config:set APP_KEY=…

将应用推送到 Heroku 上#

接下来,让我们把代码部署到 Heroku 上:
$ git push heroku master
有如下输出则代表代码推送成功:
Counting objects: 4, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 379 bytes | 0 bytes/s, done.
Total 4 (delta 3), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Fetching custom git buildpack... done
remote: -----> PHP app detected
remote: -----> Resolved 'composer.lock' requirement for PHP to version 5.6.14.
remote: -----> Installing system packages...
remote:        - PHP 5.6.14
remote:        - Apache 2.4.10
remote:        - Nginx 1.6.0
remote: -----> Installing PHP extensions...
remote:        - mbstring (composer.lock; bundled)
remote:        - zend-opcache (automatic; bundled)
remote: -----> Installing dependencies...
remote:        Composer version 1.0.0-alpha10 2015-04-14 21:18:51
remote:        Loading composer repositories with package information
remote:        Installing dependencies from lock file
...
remote:          - Installing laravel/framework (v5.1.19)
remote:            Downloading: 100%
remote:
remote:        Generating optimized autoload files
remote:        Generating optimized class loader
remote:        Compiling common classes
remote: -----> Preparing runtime environment...
remote: -----> Discovering process types
remote:        Procfile declares types -> web
remote:
remote: -----> Compressing... done, 74.5MB
remote: -----> Launching... done, v5
remote:        https://mighty-hamlet-1982.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/mighty-hamlet-1982.git
   1eb2be6..1b70999  master -> master
代码推送成功之后,使用此命令可快速打开线上应用:
$ heroku open
至此,我们便完成了一个 Laravel 应用的部署,十分简单对吧!这就是为什么大家都说 Heroku 牛逼的原因!因为这他妈的确实就是牛逼!

参考文档:

from : https://laravel-china.org/topics/2602

Deploying a Laravel Application to Heroku

Heroku is without a doubt my favorite hosting solution, insomuch that I’m currently writing another book devoted entirely to the topic (see “Easy Heroku for Busy Rails Developers”). Heroku is a cloud platform as a service (PaaS) that in the years since its founding has become a darling of the Ruby on Rails community, however the Heroku team hasn’t shied away from expanding its offerings and now supports Clojure, Java, Node.js, and PHP, among other languages.
If you’re experimenting with Laravel or are planning on managing a relatively small project, you might find Heroku particularly compelling in that it offers a free entry level hosting tier. If your hosting requirements are somewhat more ambitious then you’ll want to take the time to carefully review Heroku’s pricing optionsas the bills can add up rather quickly. However Heroku really does live up to the adage, “you get what you pay for”, because in my opinion they offer unsurpassed service. If anything, it doesn’t hurt to create a free Heroku account and follow along with the deployment instructions described in this section; you can always easily delete the deployment if you later decide Heroku isn’t for you.

Creating a Heroku Account

To get started, you’ll first need to create a new Heroku account (https://signup.heroku.com). Doing so is free and only takes a quick moment to do. At registration time you’ll be prompted to choose your desired development language. Go ahead and choose PHP however keep in mind doing so doesn’t limit your ability to later use Heroku in conjunction with other supported languages.

Installing the Heroku Toolbelt

After creating your account you’ll next need to install the Heroku Toolbelt (https://toolbelt.heroku.com/). The Heroku Toolbelt is a terminal utility you’ll use to manage various aspects of your Heroku-hosted project, including the actual deployment process, migrating your database, and interacting with the Heroku servers in various ways. To install the Heroku Toolbelt, head on over to https://toolbelt.heroku.com/, where you’ll find either download binaries or installation instructions for OS X, Windows, Debian/Ubuntu, and other Linux distributions.
Once installed, open a terminal and execute heroku:
$ heroku
Usage: heroku COMMAND [--app APP] [command-specific-options]

Primary help topics, type "heroku help TOPIC" for more details:

addons    #  manage addon resources
apps      #  manage apps (create, destroy)
...
update       #  update the heroku client
version      #  display version
You’ll be greeted with a lengthy list of commands. Introducing all of these commands is well out of the scope of this chapter, however feel free to take a moment to read the command descriptions and learn more about them by executing heroku help and then the name of the command (e.g. heroku help logs).

Deploying Your Application

With your Heroku account created and the Heroku Toolbelt installed, it’s time to deploy a Laravel application. As you’ll soon see, this is incredibly easy to do. For purposes of this example let’s just deploy a new application:
$ composer create-project laravel/laravel dev.herokutest.com dev-develop
Installing laravel/laravel (dev-develop 083db95...dac46617)
  - Installing laravel/laravel (dev-develop develop)
  Cloning develop
...
Compiling views
Do you want to remove the existing VCS (.git, .svn..) history? [Y,n]? Y
Application key [9UCBk7IDjvAGrkLOUBXw43yYKlymlqE3Y] set successfully.
With the project created, you’ll next want to create a Procfile, placing this file in your Laravel project’s root directory. The file’s capitalization is important, and it should not have an extension. Heroku reads this Procfile to determine what types of processes should launch when your application is deployed to one of their servers. In the case of a Laravel application we want to declare a web process type, identify the web server used to serve the application, and identify the application’s document root directory, which in the case of Laravel is public. Therefore the Procfile should consist of the following single line:
web: vendor/bin/heroku-php-apache2 public
Incidentally, other options are available; see the Heroku PHP documentation for more information about what’s available.
After saving these changes to the newly created Procfile, you’ll want to place your project under version control using Git:
$ git init
Initialized empty Git repository in /Users/wjgilmore/Software/dev.herokutest.com/.git/
$ git add .
$ git commit -m "First commit"
You’ll want to use Git in particular because not only do all new Laravel projects come with some Git-specific features (.gitignore files in the appropriate directories, namely), but Heroku will also interact with your local Git repository to make deployment even easier than it otherwise would be. If you’re not familiar with Git I suggest reading at least the first few chapters of “Pro Git” (free to read online) and checking out the interactive Git tutorial at https://try.github.io/.
With your repository created, it’s time to deploy! Use the Heroku Toolbelt to initialize a new Heroku project:
$ heroku create
Creating lit-retreat-6653... done, stack is cedar-14
https://lit-retreat-6653.herokuapp.com/ | https://git.heroku.com/lit-retreat-6653.git
Git remote heroku added
Note how this command created a new name for your application (in my case, lit-retreat-6653), and then identified a URL where the application can be accessed. If you head over to your project’s URL now, you’ll see a standard Heroku welcome placeholder.
Additionally, it created a Git “remote”. A remote repository is simply a Git repository for your project that resides somewhere else. You can push changes to these repositories, and pull changes from them. In the case of Heroku we’ll only ever push changes to the newly created Git remote. I’ll show you how to push these changes in just a moment but first we need to make one quick configuration change. Namely, you need to tell Heroku what buildpack to use. Buildpacks tell Heroku more about the software that should be configured on the server when your application is installed. You can do so using the Heroku Toolbelt’s config:addcommand:
$ heroku config:add \
> BUILDPACK_URL=https://github.com/heroku/heroku-buildpack-php
Setting config vars and restarting lit-retreat-6653... done, v5
BUILDPACK_URL: https://github.com/heroku/heroku-buildpack-php
Finally, it’s time to deploy! You can push your local changes to this remote by executing the following command:
$ git push heroku master
Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 416 bytes | 0 bytes/s, done.
Total 5 (delta 4), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Fetching custom git buildpack... done
remote: -----> PHP app detected
remote: -----> No runtime required in composer.json, defaulting to PHP 5.6.5.
remote: -----> Installing system packages...
...
remote: -----> Launching... done, v6
remote:        https://lit-retreat-6653.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/lit-retreat-6653.git
   4ece26b..938feb8  master -> master
Congratulations! Your application has been deployed. Head on over to your designated URL and you should see the default Laravel splash page.
Keep in mind the URL generated when you created the Heroku application is just for testing purposes; you can easily swap it out with a custom domain. See the Heroku documentation for more details.

Migrating Your Database

If you’ve been closely following along and deployed a brand new Laravel application, then presumably you successfully saw the default splash page load to your designated Heroku URL. However, if your project is backed by a database, then you’ll additionally need to at a minimum ensuring that any outstanding migrations are executed following deployment. However, if this is your first interaction with Heroku in the context of the new application, you’ll need to provision the database, which you can do with the Heroku Toolbelt:
$ heroku addons:add heroku-postgresql:hobby-dev
Adding heroku-postgresql:hobby-dev on lit-retreat-6653... done, v8 (free)
Attached as HEROKU_POSTGRESQL_NAVY_URL
Database has been created and is available
 ! This database is empty. If upgrading, you can transfer
 ! data from another database with pgbackups:restore.
Use `heroku addons:docs heroku-postgresql` to view documentation.
This command creates a new PostgreSQL database. Specifically, this database is identified by the plan Hobby Dev, which is free but has some significant limitations (notably a limit of 10,000 rows). If you are interested in using Heroku for any long term project I strongly suggest carefully learning more about the various PostgreSQL plans here.
If you’re wondering why I chose to create a PostgreSQL database rather than for instance a MySQL database, it’s because Heroku doesn’t support MySQL out of the box. However, Heroku does support MySQL. Although Heroku does indeed prominently feature its PostgreSQL support, you can in fact use MySQL via the ClearDB addon. However for reasons of convenience I’ll stick to using PostgreSQL in this section if for any other reason because you’ll find the majority of Heroku’s documentation tends to be PostgreSQL-centric.
With the database created, execute the following command to learn more about your database’s access credentials:
$ heroku config --app lit-retreat-6653 | grep DATABASE_URL
DATABASE_URL: postgres://USERNAME:PASSWORD@HOSTNAME:PORT/DATABASE
In the command output I’ve swapped out my access credentials with placeholders so you can easily identify the constituent parts. However, you don’t actually need to write these down, because the DATABASE_URLvariable is automatically stored in your server’s configuration settings. In order to transparently manage your database configuration variables in both the development and production environments, you could save yourself quite a bit of hassle by using PostgreSQL locally and saving an identically-formatted environment variable within your local environment.
Obviously you’ll also need to install and configure PostgreSQL within your local environment if it’s not already available. See http://www.postgresql.org/ for installation instructions.
Exactly how you’ll do this will depend upon your particular operating system, so consult the appropriate online documentation for more details. However, once the local environment variable is in place there are a variety of ways you can reference it within your code. One of the most straightforward ways involves parsing the variable as a URL using PHP’s parse_url() function directly within the config/database.php file. Also, you’ll need to set the database default to pgsql:
'default' => 'pgsql',

...

'pgsql' => [
    'driver'   => 'pgsql',
    'host'     => parse_url(getenv("DATABASE_URL"))["host"],
    'database' => substr(parse_url(getenv("DATABASE_URL"))["path"], 1),
    'username' => parse_url(getenv("DATABASE_URL"))["user"],
    'password' => parse_url(getenv("DATABASE_URL"))["pass"],
    'charset'  => 'utf8',
    'prefix'   => '',
    'schema'   => 'public',
],
EX : 
if(!empty(getenv("DATABASE_URL"))){    $url = parse_url(getenv("DATABASE_URL"));    $host = $url["host"];    $username = $url["user"];    $password = $url["pass"];    $database = substr($url["path"], 1);}else{    $host = env('DB_HOST', 'localhost');    $username = env('DB_USERNAME', 'forge');    $password = env('DB_PASSWORD', '');    $database = env('DB_DATABASE', 'forge');}

Save the changes and consider creating a model and corresponding migration to confirm you’re able to properly connect to the new PostgreSQL database. After doing so, commit your changes and push them to Heroku:
$ git add .
$ git commit -m "Updated database configuration"
$ git push heroku master
Next, you’ll want to migrate the database. You can easily do this using the Heroku Toolbelt’s run command:
$ heroku run php artisan migrate --app lit-retreat-6653
Running `php artisan migrate` attached to terminal... up, run.6981
**************************************
*     Application In Production!     *
**************************************

Do you really wish to run this command? [y/N] y
Migration table created successfully.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2015_01_30_032004_create_todolists_table.php
Your migrations are now in place!

Summary

Although Heroku is traditionally known for its fantastic Ruby on Rails support, my experience with this fantastic hosting service indicates it will soon become equally respected among the PHP community. If you have deployed PHP/Laravel applications on Heroku, share your thoughts in the comments!

from : http://www.easylaravelbook.com/blog/2015/01/31/deploying-a-laravel-application-to-heroku/

2016年10月10日 星期一

Using MySQL on Heroku

How to install a MySQL Heroku Add-on and use it with Laravel

This guide is a follow-up to Laravel & Heroku Workflow so if you haven’t read that yet,read it now.
So we’ve created a new heroku app, now let’s install MySQL. First, open your apps listinghere and choose the app you want to install MySQL on.
You should now see something like this
Heroku Dashboard
In the Add-ons search field, type ClearDB MySQL and select it. Choose the free plan (Ignite) and click provision.
So now you’ve got MySQL installed, now we need to set it up so the app uses our local env config on our machine and our heroku db config when we deploy to heroku.
Go to your apps listing on heroku and choose your app. Click on the Settings tab. You should now see a config tab like in the picture below.
Config
Click Reveal Config Vars and copy the CLEARDB_DATABASE_URL value.
I’ll use mine as an example: mysql://b419fdf6d21e11:c78bdf37@us-cdbr-iron-east-02.cleardb.net/heroku_f7469a0c6b39995?reconnect=true.
Everything after the @ symbol until the / is the DB_HOST, us-cdbr-iron-east-02.cleardb.net
Everything after / until ? is DB_DATABASE, heroku_f7469a0c6b39995
The string after the // until : is the DB_USERNAME, b419fdf6d21e11
The string between : and @ is the DB_PASSWORD, c78bdf37
Now that we have our heroku DB credentials, let’s update our database.php file so that the app can access the ClearDB database when deployed to heroku.
My credentials now look like this.
'mysql'  => [
    'driver'    => 'mysql',
    'host'      => env('DB_HOST', 'us-cdbr-iron-east-02.cleardb.net'),
    'database'  => env('DB_DATABASE', 'heroku_f7469a0c6b39995'),
    'username'  => env('DB_USERNAME', 'b419fdf6d21e11'),
    'password'  => env('DB_PASSWORD', 'c78bdf37'),
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'strict'    => false,
],
Since I’m using Laravel 5.2 at the moment, I’ll run php artisan make:auth so that I get out of the box migrations for auth.
Now we can git add . && git commit -m "Added DB Config", and afterwards we can run git push heroku master.
Side Note: If you want to run any command directly on your heroku server, you need to prepend the regular command with heroku run, inside your project directory.
For example, if you want to run php artisan inspire on your heroku server you would run heroku run php artisan inspire.
Now go ahead and run heroku run php artisan migrate:refresh to run the migrations on the heroku server.
And just like that, you have a working staging environment with a MySQL database ready to go.
Note: ClearDB has an auto-increment value of 10 so the record ID’s will range from 2, 12, 22 and so on. The Ignite plan has a maximum database size of 5MB.

from : http://selimsalihovic.github.io/2016-02-07-using-mysql-on-heroku/

Laravel on Heroku - Using a Buildpack locally to mimic your Heroku environment (Nginx)

(This is part of a series of posts on Laravel on Heroku. Check back soon for more.)
  1. Installing a Laravel app on Heroku
  2. Laravel on Heroku - Using a MySQL database
  3. Laravel on Heroku - Using a PostgreSQL database
  4. Laravel on Heroku - Using a Buildpack locally to mimic your Heroku environment (Nginx)
So by this point you've got your app and running, and deployed to Heroku. You probably even have a ClearDB MySQL database connected to it on Heroku.
But your local environment and database are not particularly in sync with your production environment. Thankfully, Heroku provides the ability to run their "buildpacks" locally to ensure a local environment that's in sync with your remote environment.
Note: I wrote a blog post to get this running on a local Apache install, but the number of steps and configuration issues it required was out of reach for a simple tutorial. The folks at Heroku have shared that they're in the middle of making changes to the Apache configuration for the buildpack, so I expect it'll get easier soon. For now, let's roll with Nginx.
Open up your app's composer.json and add the following to the end of it (or just add the buildpack to your require-dev section, if you already have one):
  "require-dev": {
    "heroku/heroku-buildpack-php": "dev-master"
  }
Run composer update, and you'll now have the Heroku PHP Buildpack installed locally. Now, create a file in your project root directory named .env and place the following code into it:
CLEARDB_DATABASE_URL=mysql://root:123abc@127.0.0.1/my_laravel_heroku_database_name
This file is a configuration file for the Buildpack, setting an environment var named CLEARDB_DATABASE_URL and setting its value to mysql://root:123abc@127.0.0.1/my_laravel_heroku_database_name. This version we created is just for local testing, so add it to your .gitignore.
Note that you'll need to update the username (root), password (123abc), and database name (my_laravel_heroku_database_name) for your local environment. Heroku's local buildpack won't be serving MySQL for you, so you'll need MySQL running.
NOTE: If you don't have a command-line mysql accessible and working, Mac/Homebrew users can brew install mysql and then follow the directions to have launchd start mysql at login. I believe the default username is root and the default password is blank.
Finally, run foreman start (unfamiliar with Foreman? Check out my blog post introducing Procfiles) to get everything up and running.
Note: If you get the following response: This program requires PHP 5.5.11 or newer; check your 'php' command., it means your local version of PHP is not up to date with what Heroku is expecting. Run php -von the command line to find what version you're running. Hopefully you're on a Mac using Homebrew, because if you are it's a relatively painless fix: run brew update, then brew install --with-fpm php55 and then `brew install php55-mcrypt'. Follow the instructions that are output after you run the installer and you should have PHP 5.5 up and running shortly.
You'll now have a CLEARDB_DATABASE_URL env var available for use in your local database.php just like we did in the production database.php (but note we've added a bit to the code to allow for null passwords locally). The benefit of using the .env file like is this it that we can use the same database.php on dev and prod, and just rely on the .env file to change up the database credentials:
$url = parse_url(getenv("CLEARDB_DATABASE_URL"));

$host = $url["host"];
$username = $url["user"];
$password = array_key_exists('pass', $url) ? $url["pass"] : '';
$database = substr($url["path"], 1);

return array(
    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => $host,
        'database'  => $database,
        'username'  => $username,
        'password'  => $password,
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    )
);
With that, you have a development-ready local environment that mimicks the Heroku PHP buildpack. Just visit localhost:5000 in your browser and you're good to go!

from : https://mattstauffer.co/blog/laravel-on-heroku-using-a-buildpack-locally-to-mimic-your-heroku-environment-nginx

wibiya widget