title: Rails app cannot connect to postgresql but rake, rails c, and rails db can
body: <h2>Problem</h2>
  
  <p>Hitting my rails app in production results in a 500 error. Checking the production log results in: <a href="https://gist.github.com/jonlunsford/5462023" rel="nofollow">gist</a>. Checking the verbose postgresql log results in: <a href="https://gist.github.com/jonlunsford/5462096" rel="nofollow">gist</a> (actual db creds have been replaced). The postgres logs are showing the port number increment every connection attempt despite what's specified in the database.yml file.</p>
  
  <h2>Environment</h2>
  
  <p><strong>Server</strong>: Ubuntu 12.10 (GNU/Linux 3.5.0-17-generic i686)</p>
  
  <p><strong>Rack Server:</strong> Unicorn  </p>
  
  <p><strong>Rails v:</strong> 3.2.13</p>
  
  <p><strong>Ruby v:</strong> 1.9.3p0 (really old, perhaps a problem here?)</p>
  
  <h2>What I've Tried</h2>
  
  <p><strong>Double check database.yml:</strong><br>
  Tried w/ and w/o host and port, checked indentation and validated yaml formatting.</p>
  
  <pre><code>production:
    adapter: postgresql
    database: &lt;db_production&gt;
    username: &lt;db_user&gt;
    password: &lt;db_password&gt;
    host: localhost
    port: 5432 
  </code></pre>
  
  <p><strong>Run rake, rails c, and rails db:</strong><br>
  I can log in and successfully run all of these commands. I am having to specify the environment here, perhaps this is the issue? is the environment not getting set somehow?</p>
  
  <pre><code>bundle exec rails db production
  </code></pre>
  
  <p>running:  </p>
  
  <pre><code>Rails.env?
  </code></pre>
  
  <p>results in production, but this is after explicitly logging into rails c production.</p>
  
  <p><strong>Change pg_hba.conf</strong>:<br>
  I have tried several settings I've found in other SO questions. The original settings for local were:  </p>
  
  <pre><code>local    all    all    peer
  </code></pre>
  
  <p>Then tried:</p>
  
  <pre><code>local    all    all    md5
  </code></pre>
  
  <p>Then tried:</p>
  
  <pre><code>local    all    all    trust
  </code></pre>
  
  <p>After all of these changes I made sure to either restart pg or pg_ctl reload to pickup the changes.</p>
  
  <p><strong>Log into pg outside or rails:</strong><br>
  Even after each change to pg_hba.conf I can still login to my production database with the same creds in database.yml and see all of my data, and confirm all migrations and db creations have run.</p>
  
  <p>running:</p>
  
  <pre><code>sudo -u &lt;db_user&gt; psql &lt;db_production&gt;
  </code></pre>
  
  <p>works as expected.</p>
  
  <h2>Conclusion</h2>
  
  <p>It's obvious to me that the problem is not with postgres but with the rails config, perhaps the environment isn't switching to production and thus it's trying to use dev db creds? which don't exist in my production yml file.</p>