如何在heroku上设置生产环境变量?

时间:2016-04-16 10:55:39

标签: laravel heroku laravel-5 laravel-5.2 cleardb

我想在heroku上使用MySQL运行应用程序。我已经为此安装并配置了cleardb。我剩下要做的就是配置环境变量。但是,我找不到合适的方法来做到这一点。

在这个article中,Matt解释了如何配置上述变量:

// config/database.php

$url = parse_url(getenv("CLEARDB_DATABASE_URL"));

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

// . . .

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => $host,
    'database'  => $database,
    'username'  => $username,
    'password'  => $password,
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

他还说:

  

如果您真的在真实网站上工作,那么您应该确定   您只是专门为您的数据库编辑数据库凭据   生产环境

那么,在生产中如何配置环境变量以在heroku上使用cleardb运行MySQL?

2 个答案:

答案 0 :(得分:4)

Being tagged as Laravel 5.2, you need to set the environment variable in the .env file. This file is not included in version control, because you are supposed to have different versions on each installation. A .env.example is provided by default.

As an example, if your URL is:

CLEARDB_DATABASE_URL => mysql://adffdadf2341:adf4234@us-cdbr-east.cleardb.com/heroku_db?reconnect=true

then in your .env file you can put:

DB_CONNECTION=mysql
DB_HOST=us-cdbr-east.cleardb.com
DB_PORT=3306
DB_DATABASE=heroku_db
DB_USERNAME=adffdadf2341
DB_PASSWORD=adf4234

and leave the config/database.php untouched.

The other solution would be to define the URL above in the .env file and parse it dynamically as suggested. Note that these variables are accessed using env("CLEARDB_DATABASE_URL").

EDIT

Since the CLEARDB_DATABASE_URL is set automatically, it will probably be better to make use of it.

// config/database.php

if ($url = env('CLEARDB_DATABASE_URL', false)) {
    $parts = parse_url($url);
    $host = $parts["host"];
    $username = $parts["user"];
    $password = $parts["pass"];
    $database = substr($parts["path"], 1);
} else {
    $host = env('DB_HOST', 'localhost');
    $username = env('DB_USERNAME', 'forge');
    $password = env('DB_PASSWORD', '');
    $database = env('DB_DATABASE', 'forge');
}

// ...
        'mysql' => [
            'driver' => 'mysql',
            'host' => $host,
            'database' => $database,
            'username' => $username,
            'password' => $password,
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
        ],

答案 1 :(得分:0)

在Heroku上设置环境变量非常简单。 您可以使用Heroku CLI,如下所示:     heroku config:设置CLEARDB_DATABASE_URL =“你的DB URL”

您还可以通过Heroku仪表板轻松配置环境变量。