---
# System prepended metadata

title: 'Linux - ERROR 2002 (HY000): Can''t connect to local MySQL server through socket ''/var/run/mysqld/mysqld.sock'' (2) 解決方式'
tags: [Linux, MySQL]

---

# Linux - ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) 解決方式

>參考：[color=#00FF00] https://iter01.com/566142.html

安裝mariadb-server
```
apt install mariadb-server
```

在'/etc'建立'my.cnf'檔案
```
$ touch 'my.cnf' // 建立檔案
$ vi 'my.cnf' // 修改檔案
```
新增以下內容
```
[mysqld] 
datadir=/usr/local/mysql/data 
socket=/var/lib/mysql/mysql.sock 

[mysql.server] 
user=mysql 
basedir=/usr/local/mysql 

[client] 
socket=/var/lib/mysql/mysql.sock 
```

重新啟動服務
```
service mysql restart
```


## 新建使用者及資料庫

>參考：[color=#00FF00]https://www.opencli.com/mysql/mysql-add-new-users-databases-privileges

用 MySQL 的 root 帳號連接到 MySQL:
```
# mysql -u root -p
Enter password:
```

為新帳號建立資料庫
```
mysql> CREATE DATABASE `database`;
Query OK, 1 row affected (0.00 sec)
```

建立 MySQL 新帳號
```
mysql> CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';
Query OK, 0 rows affected (0.00 sec)
```

給予新帳號權限讀寫新資料庫
```
mysql> GRANT ALL PRIVILEGES ON `database`.* TO 'user'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
mysql> quit
```

設定完成後登入測試
```
# mysql -u user -p
Enter password:
```
