mysql 対処法:Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

先日、rails で新しくアプリ開発をした時、rake db:create コマンドで Error: Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2) がでたので、その対処法をメモ。


$ rake db:create

で、以下のエラーが発生。


#<Mysql2::Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)>
Couldn't create database for {"adapter"=>"mysql2", "encoding"=>"utf8", "pool"=>5, "username"=>"root", "password"=>nil, "host"=>"localhost", "database"=>"project_development"}, {:charset=>"utf8", :collation=>"utf8_unicode_ci"}
(If you set the charset manually, make sure you have a matching collation)
#<Mysql2::Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)>
Couldn't create database for {"adapter"=>"mysql2", "encoding"=>"utf8", "pool"=>5, "username"=>"root", "password"=>nil, "host"=>"localhost", "database"=>"project_test"}, {:charset=>"utf8", :collation=>"utf8_unicode_ci"}
(If you set the charset manually, make sure you have a matching collation)

すでにプロセスが起動していることで指定のソケットファイルがすでに使用されていて、新たにプロセスが起動できない状態でした。


$ mysql.server stop
$ mysql.server start

それでもだめなら、


$ sudo rm /tmp/mysql.sock
$ mysql.server stop
$ mysql.server start

そしてから


$ bundle exec rake db:create

解決。
すでにプロセスが起動していたことが原因だった。
bundle exec をつけると、Rails プロジェクトの Gemfile で指定した環境下で実行する事が可能になる。