Gabriel Carneiro
Gabriel Carneiro

Reputation: 85

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

Recently I tried to change the database of my Rails application. I was using sqlite3 and I wanted to change it to MySQL. I followed the steps of this tutorial : https://guides.rubyonrails.org/configuring.html#configuring-a-mysql-or-mariadb-database

This is my database.yml :

default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  adapter: mysql2
  encoding: utf8mb4
  database: blog_development
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

production:
  adapter: mysql2
  advisory_locks: false

What caused this following error : Mysql2::Error::ConnectionError: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) and what I need to do to fix it ?

Upvotes: 1

Views: 4693

Answers (2)

Cleber Reizen
Cleber Reizen

Reputation: 475

Check your syslog to see where is the socket location. In my case is "run/mysqld/mysqld.sock". Then edit the database.yml file.

From

socket: /tmp/mysql.sock

to

socket: /run/mysqld/mysqld.sock

Upvotes: 0

Jo&#227;o Fernandes
Jo&#227;o Fernandes

Reputation: 741

Reading your latest comment, I've noticed that you've got a new error:

#<Mysql2::Error::ConnectionError: Access denied for user 'root'@'localhost' (using password: NO)>

You've left your password field under the development environment empty. All you need to do is to fill the password with the same password you set while installing mysql2, it should do it.

In case you can't remember your password, check this guide:

Resuming the guide, you should:

sudo service mysql stop
sudo mysqld_safe --skip-grant-tables --skip-networking &
mysql -u root

Once inside MySQL, you shall type:

use mysql;
update user set authentication_string=password('NEWPASSWORD') where user='root';
flush privileges;
exit

This should do it. If you ever want to log into MySQL once again, you shall type:

mysql -u root -p NEWPASSWORD

The -p stands for password.

I'd recommend against using your password directly on database.yml file. It's safer to set an environment variable with your password and then using it on database.yml, like this:

  username: <%= ENV.fetch("username") %>
  password: <%= ENV.fetch("password") %>

If this is the case and you are running Linux, you must update your environment variables under /etc/environment. Under /etc/environment you must have something like this:

username=MYSQL_USERNAME_HERE
password=MYSQL_PASSWORD_HERE

Upvotes: 0

Related Questions