Jörg Haubrichs
Jörg Haubrichs

Reputation: 2243

Problems connecting to remote MySQL host with Rails

I wanted to connect to a remote MySQL host (with rake db:create), but Rails always considers it to be local. Database.yml which uses the following config:

defaults: &defaults
  encoding: unicode
  adapter: mysql
  username: <username>
  password: *************
  port: 3306
  host: <remote ip address>

development:
  <<: *defaults
  database: <db name>
test: &test
  <<: *defaults
  database: <db name>
production:
  <<: *defaults
  database: <db name>

And always get this error when trying anything on the database:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

The config works as long as I use the local database (i.e. without the host/port part). Connecting to the remote MySQL server works fine with the given details.

Any ideas on what is going wrong ?

Edit: The problem only occurs with rake:db:create, other tasks work - The error message was really badly misleading.

Upvotes: 6

Views: 8199

Answers (2)

andyjeffries
andyjeffries

Reputation: 1

I found the same thing. I was using this:

RAILS_ENV=production bundle exec rails console

And it was complaining about not being able to find /tmp/mysql.sock (which is only in the development section of database.yml). If I checked Rails.env from the console it correctly said production. The fix is as simple as:

RACK_ENV=production bundle exec rails console

Upvotes: 0

Yeameen
Yeameen

Reputation: 833

You may need to enable MySQL server to accept remote request (by binding to host's ip address or all address format 0.0.0.0). Edit MySQL configuration file my.cnf on the remote host. In Ubuntu, you can find the file in /etc/mysql/my.cnf

Change the value of bind-address:

bind-address            = 0.0.0.0

Upvotes: 1

Related Questions