【问题标题】:Ubuntu and Rails PostgreSQL setupUbuntu 和 Rails PostgreSQL 设置
【发布时间】:2016-02-23 16:53:07
【问题描述】:

我在 Ubuntu 14.04 LTS 机器上。
我在 help.ubuntu.comHerokudigitalocean.com 找到了有关如何在 Ubuntu 中为 Rails 开发配置 PostgreSQL 的有用信息。

将所有内容放在一起,所有信息似乎都集中在创建数据库超级用户的必要性上,其登录名与我的 Ubuntu 用户名匹配:
sudo -u postgres createuser --superuser $USER

当时间到了为新的超级用户创建密码 sudo -u postgres psql 时,我想知道 Rails 是否可以在不设置密码的情况下使用 PostgreSQL,这个密码是否可以而且应该与我的 Ubuntu 帐户密码不同,以及 @987654329 是否在推送到托管网站的 Git 存储库和 Heroku 时,@ 可能是一个安全问题。
indatabase.yml其实就是记录了这种敏感信息。

According to Heroku 必须“导出 DATABASE_URL 环境变量,以便您的应用在本地运行时连接到它”,使用:export DATABASE_URL=postgres:///$(whoami)
这真的有必要吗? help.ubuntu.comdigitalocean.com 未报告此信息。

最后我想知道选择通过 PostgreSQL apt 存储库安装 PostgreSQL 是否足够安全,还是最好安装 LTS 版本的 Ubuntu。

【问题讨论】:

    标签: ruby-on-rails postgresql ubuntu heroku


    【解决方案1】:

    Rails 有两种方式设置与数据库的连接:通过config/database.yml 或通过环境变量ENV['DATABASE_URL']。见guides.rubyonrails.org
    默认$DATABASE_URL 为空:

    echo $DATABASE_URL
    

    如果通过 PostgreSQL apt 存储库安装 posgresql,为了让 Rails 使用 pg gem,还需要安装 libpq-dev 包,否则 bundle install 将失败。见Can't find the 'libpq-fe.h header when trying to install pg gem

    来自“man createuser”:

       createuser creates a new PostgreSQL user (or more precisely, a role). Only superusers and users with
       CREATEROLE privilege can create new users, so createuser must be invoked by someone who can connect as a
       superuser or a user with CREATEROLE privilege.
    

    安装 postgresql 后,它会创建一个用户 postgres,其角色为 postgres。它还会创建一个postgres 系统帐户。 所以这就是为什么createuser应该作为postgres用户运行,以便第一次连接到postgresql并添加用户$USER(当前系统用户)。

    不必为新的数据库用户创建密码。大多数人将database.yml 添加到他们的.gitignore 文件中,这样它就不受版本控制。也可以使用.pgpass保持敏感 *.yml 文件中的信息:参见postgresql documentation

    只能作为数据库用户并通过现有数据库连接到 postgresql。 在从 postgresql apt 存储库安装期间,postgresql 仅创建 postgres 用户和 postgres 数据库。
    psql 命令允许当前用户连接到以当前用户命名的 postgresql 数据库。因此,如果系统用户是“dave”并且有一个“dave”数据库,则“dave”可以使用命令psql 连接到“dave”数据库而没有选项。
    如果 'dave' 是数据库用户,但没有创建数据库 'dave',为了让 dave 连接到 postgresql,必须指定一个现有数据库:

    psql -d postgres
    

    或者,dave 可以使用sudopostgres 用户身份连接到执行psql 命令的postgresql:

    sudo -u postgres psql
    

    【讨论】: