Не удается подключиться к локальному серверу mysql через сокет
I installed LAMP on Ubuntu 12.04 LTS (Precise Pangolin) and then set root password on phpMyAdmin. I forgot the password and now I am unable to login. When I try to change password through terminal I get:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
How can I fix this? I am unable to open LAMP, uninstall it or reinstall it.
Start or restart mysql service and check. sudo /etc/init.d/mysql start or sudo /etc/init.d/mysql restart
MySQL продолжает «падать»
Если такая проблема возникает, необходимо выяснить, заключается она в сервере или в клиенте. Обратите внимание, что многие сбои сервера вызваны повреждёнными файлами данных или индексными файлами.
Вы можете проверить состояние сервера, чтобы определить, как долго он работал.
Чтобы узнать время безотказной работы сервера, запустите команду mysqladmin .
Кроме того, можно остановить сервер, сделать отладку MySQL и снова запустить службу. Для отображения статистики процессов MySQL во время выполнения других процессов откройте окно командной строки и введите следующее:
Убедитесь, что MySQL/MariaDB сервер установлен
В первую очередь убедитесь, что СУБД MySQL или MariaDB вообще установлены.
Пакет может называться mysql-server или mysql. Если вы выбрали MariaDB вместо MySQL, то пакет называется mariadb-server или mariadb.
Пакеты mysql-client или mariadb-clients или какие-то ещё НЕ подходят! Это только клиенты для подключения, но не сам сервер.
На Ubuntu, Linux Mint и других дистрибутивах из этой семьи для установки выполните:
Убедитесь, что служба MySQL/MariaDB запущена
Файл /run/mysqld/mysqld.sock создаётся когда MySQL или MariaDB сервер установлен и запущен. Поэтому проверим статус сервера следующей командой (подходит и для MySQL, и для MariaDB):
Должен быть статус active (running) .
Если служба не запущена, то запустите её командой:
После этого проверьте статус службы
Добавления службы в автозагрузку (чтобы не пришлось её запускать при каждом включении компьютера, выполните следующую команду):
Недостаточно памяти
Если такая ошибка возникла, это может означать, что в MySQL недостаточно памяти для хранения всего результата запроса.
Сначала нужно убедиться, что запрос правильный. Если это так, то нужно выполнить одно из следующих действий:
- если клиент MySQL используется напрямую, запустите его с ключом --quick switch , чтобы отключить кешированные результаты;
- если вы используете драйвер MyODBC, пользовательский интерфейс (UI) имеет расширенную вкладку с опциями. Отметьте галочкой «Do not cache result» (не кешировать результат).
Также может помочь MySQL Tuner. Это полезный скрипт, который подключается к работающему серверу MySQL и даёт рекомендации по настройке для более высокой производительности.
Заключение
Самое важное при диагностике — понять, что именно вызвало ошибку. Следующие шаги помогут вам в этом:
I am having a big problem trying to connect to mysql. When I run:
I have the following error :
I do have mysql.sock under the /var/mysql directory.
In /etc/my.cnf I have:
and in /etc/php.ini I have :
I have restarted apache using sudo /opt/local/apache2/bin/apachectl restart
But I still have the error.
Otherwise, I don't know if that's relevant but when I do mysql_config --sockets I get
That certainly explains the error in trying to connect to it. How, as @Romain mentioned, is there anything in MySQL's logs (try /var/log/mysql or somewhere around there) which indicates why it isn't running? Do you get an error when you try to start it?
I was getting the same error, but in my case, I found out mysql wouldn't start because the disk was 100% full. /var/log/mysqld.log was helpful.
the reason they are asking if it is running, i presume, is because the socket is made when the service starts. i installed mysql, but never started the service, so the .sock file doesn't exist. type service mysqld start if you just installed. hth
To reset the password
Follow these steps (can be helpful if you really forget your password and you can try it anytime, even if you're not in the situation at the moment):
Or for other distribution versions:
Start MySQL in safe mode
Log into MySQL using root
Select the MySQL database to use
Reset the password
Flush the privileges
Restart the server
Stop and start the server again
Ubuntu and Debian:
On CentOS, Fedora, and RHEL:
Login with a new password
Type the new password and enjoy your server again like nothing happened
@JoeKreydt, in v.8 it is also possible to use the original example for v.5.7+, however with the minor adaptation of providing the new password value without the surrounding passowrd() argument.
I tried the following steps:
- Log in as super user or use sudo
- Open /etc/mysql/my.cnf using gedit
- Find bind-address , and change its value to the database server host machine's IP address. For me, it was localhost or 127.0.0.1
- Save and close the file.
- Come back to terminal and execute sudo service mysql start
And it worked for me.
@rshahriar there is nothing called as bind-address in my /etc/my.cnf is it a good idea to add the field
restarting the mysql service worked for me as well, but still not sure where to find the error log in order to figure out the cause and try to prevent it from happening again.
In my case it was that the disk was full and mysqld couldn't start anymore.
Try to restart mysql service.
If it doesn't recognize stop command then it's definitely the disk space. You should make some space in the partition mysql is allocated or make the disk larger.
Check the disk space with
If that is your problem executing: "/etc/init.d/mysqld start" will tell you your disk partition is full
I fixed this problem by executing the following command:
And if you are on a mac and used brew to install mysql, simply use:
I had a similar problem. mysql wouldn't start:
If I disabled apparmor:
the problem went away. The issue was that mysqld was trying to access /run/mysqld/mysqld.sock but the apparmor profile only gave permission to /var/run/mysqld/mysqld.sock (/var/run is symlinked to /run, so these are actually the same). Not sure why mysqld isn't using the var path since that's what's set in all the configuration files, but you can fix the problem by adding the following to /etc/apparmor.d/usr.sbin.mysqld
I didn't know that I had to call "sudo service mysql start". Last time I installed MySQL on Ubuntu, I think it autostarted upon installation. MariaDB on Manjaro requires the service to be explicitly started after installation.
I solved this by killing the mysql process:
And then I started the server again with:
But start works as well:
Then I logged in as admin , and I was done.
well, I actually was aborting mysql before it crashes. Then I get " * Please take a look at the syslog." and "ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)". Finally, I realize it's trying to recover itself, so I kill and restart it.
There are (rare) situations where "mysql start" will fail, so you need to use the "restart" argument. If you need to kill a daemon process, its better to use the "stop" argument instead of the kill command. However, the killall command is more convenient than the kill command (killall mysqld).
Somehow the MySQL server process did not create the socket, or the client is looking for the socket in the wrong place.
My first suggestion would be to check if the MySQL server is running. Second suggestion might be, is the MySQL server running on another host? If so, add the -h flag to your MySQL client in the terminal.
If MySQL is indeed running, and running locally, check your my.cnf file. There should be a line like
See if that matches the socket location that you mentioned in your post.
From experience, I would say the most likely scenario is your MySQL server either is not running at all or is not running on the same host as where you run your MySQL client from the terminal.
MySQL — система управления базами данных (СУБД) с открытым исходным кодом от компании Oracle. Она была разработана и оптимизирована специально для работы веб-приложений. MySQL является неотъемлемой частью таких веб-сервисов, как Facebook, Twitter, Wikipedia, YouTube и многих других.
Эта статья расскажет, как определять, с чем связаны частые ошибки на сервере MySQL, и устранять их.
Служба mysqld не может запуститься из-за отсутствия места на диске
Если ваш диск переполнен, то это может быть причиной невозможности запуска службы, даже если она правильно настроена и ранее нормально работала.
Освободите пространство на диске и перезапустите службу.
Служба mysqld не запускается из-за недоступности файлов баз данных
Ещё одной причиной может стать то, что вы переместили файлы с базами данных, но не изменили пути в соответствующих файлах настройки MySQL. Выполните правильно настройку и перезапустите MySQL или MariaDB.
Не удаётся подключиться к локальному серверу
Одной из распространённых ошибок подключения клиента к серверу является «ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)».
Эта ошибка означает, что на хосте не запущен сервер MySQL ( mysqld ) или вы указали неправильное имя файла сокета Unix или порт TCP/IP при попытке подключения.
Убедитесь, что сервер работает. Проверьте процесс с именем mysqld на хосте сервера, используя команды ps или grep, как показано ниже.
Если эти команды не показывают выходных данных, то сервер БД не работает. Поэтому клиент не может подключиться к нему. Чтобы запустить сервер, выполните команду systemctl.
Чтобы проверить состояние службы MySQL, используйте следующую команду:
Если в результате выполнения команды произошла ошибка службы MySQL, вы можете попробовать перезапустить службу и ещё раз проверить её состояние.
Если сервер работает (как показано) и вы по-прежнему видите эту ошибку, вам следует проверить, не заблокирован ли порт TCP/IP брандмауэром или любой другой службой блокировки портов.
Для поиска порта, который прослушивается сервером, используйте команду netstat .
36 Answers 36
Are you connecting to "localhost" or "127.0.0.1" ? I noticed that when you connect to "localhost" the socket connector is used, but when you connect to "127.0.0.1" the TCP/IP connector is used. You could try using "127.0.0.1" if the socket connector is not enabled/working.
You can also force using a socket with the socket parameter (-S with /usr/bin/mysql) and force TCP/IP by providing a port (-P with /usr/bin/mysql.)
Using a fully qualified network name other than localhost worked for me. Just make sure it's declared in the client side 'hosts' file.
Note to cygwin users: if the cygwin mysql client tries to hook to a local WAMP mysql server for instance, use -h
A wrong hostname did give me the exact same error. Looking at the /etc/hosts file in my docker container showed me the MySql hostname to be mysql . Using this same hostname in my connect configuration resolved the issue.
Ensure that your mysql service is running
Then, try the one of the following following:
(if you have not set password for mysql)
if you have set password already
This was the answer for me. Since i'm using mariadb the solution was to run the following: "sudo systemctl start mariadb". All was well after that.
If your file my.cnf (usually in the etc folder) is correctly configured with
you can check if mysql is running with the following command:
try changing your permission to mysql folder. If you are working locally, you can try:
that solved it for me
It works for me also, but is after i upgraded to the lastest version then appear this problem, may i know why this happen?
sudo chmod -R 777 /var/lib/mysql/ Worked for me with an issue I had in starting a docker container mysql
You should not make your mysql data directory world writeable! /var/lib/mysql should be 750 and move the socket file to another directory (eg. set socket=/tmp/mysql.sock in /etc/my.cnf [mysqld] and [client] sections). Or at least set /var/lib/mysql to 755
The MySQL server is not running, or that is not the location of its socket file (check my.cnf).
Most likely mysql.sock does not exist in /var/lib/mysql/ .
If you find the same file in another location then symlink it:
For ex: I have it in /data/mysql_datadir/mysql.sock
Switch user to mysql and execute as mentioned below:
That solved my problem
renaming mysql.sock to something else, then restarting mysqld ("service mysqld restart"), then renaming something else back to mysql.sock worked for me. A slight variation on this answer, so thanks.
These literal commands did not solve the problem for my specific use case, but the concept of using a symlink to the .sock did indeed!
If you are on a recent RHEL, you may need to start mariadb (an open source mysql db) instead of the mysql db:
You should then be able to access mysql in the usual fashion:
FYI this works for CentOS 8.1 as well. After install mariadb-server and mariadb , don't forget to run mysql_secure_installation to clean up some default unsafe settings.
Just edit /etc/my.cnf Add following lines to my.cnf
Restart mysql and connect again
mysql -u user -p password database -h host;
In my case I have moved socket file to another location inside /etc/my.cnf from /var/lib/mysql/mysql.sock to /tmp/mysql.sock
Even after restarting the mysqld service, I still see the error message when I try to connect. ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
The problem is with the way that the client is configured. Running diagnostics will actually show the correct socket path. eg ps aux | grep mysqld
You can fix this problem by adding the same socket line under [client] section inside mysql config.
Check if your mysqld service is running or not, if not run, start the service.
If your problem isn't solved, look for /etc/my.cnf and modify as following, where you see a line starting with socket . Take a backup of that file before doing this update.
MariaDB, a community developed fork of MySQL, has become the default implementation of MySQL in many distributions.
So first you should start,
If this fails rather try,
Then to start mysql,
As of today, in Fedora the package is named mariadb And in Ubuntu it is called mariadb-server .
So you may have to install it if its not already installed in your system.
Make sure you have enough space left in /var . If Mysql demon is not able to write additional info to the drive the mysql server won't start and it leads to the error Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
This will help you keep disk usage down.
Thanks, I am running mysql on oracle virtualbox and when I made a dump of my bd, i run out of space, and couldn't get mysql server to start, when i deleted the dump file i was able to restart mysql server.
This solved it for me. I had innodb_buffer_pool_size set to a very high value for production environments and it made mysql crash on my virtual machine.
I had this problem when using phabricator and the solution was to change innodb_buffer_pool_size in my.cnf . Setting it to a small value like innodb_buffer_pool_size = 50M is a good test to discard this hypothesis ;)
That was the freaking problem, checked everything but disk space. Freed space from /var, it came back!
Please check whether another mysql service is running.
Here's what worked for me:
Make sure you started the server:
Then connect with root user:
If your mysql was previously working and has stopped suddenly just "reboot" the server.
Was facing this issue on my CentOS VPS.->
Was constantly getting
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'(2)
Tried all techniques, finally restarting the server fixed the issues ->
Hope this helps !!
One way to reproduce this error: If you meant to connect to a foreign server but instead connect to the non existent local one:
So you have to specify the host like this:
if you change files in /var/lib/mysql [ like copy or replace that ], you must set owner of files to mysql this is so important if mariadb.service restart has been faild
chown -R mysql:mysql /var/lib/mysql/*
chmod -R 700 /var/lib/mysql/*
First enter "service mysqld start" and login
This question was successfully answered three years ago. This exact answer was given more completely last year.
Please ensure you have installed MySQL server correctly, I met this error many times and I think it's complicated to debug from the socket, I mean it might be easier to reinstall it.
If you are using CentOS 7, here is the correct way to install it:
Then you can install it by yum install mysql-community-server
Start it with systemctl: systemctl start mysqld
My problem was that I installed mysql successfully and it worked fine.
But one day, the same error occurred.
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
And no mysql.sock file existed.
This sollution solved my problem and mysql was up and running again:
mysql should now be up and running.
I hope this can help someone else as well.
Note that while mysql reads the info of the location of the socketfile from the my.cnf file, the mysql_secure_installation program seems to not do that correctly at times.
So if you are like me and shuffle things around at installationtime you might get into the situation where you can connect to the database with mysql just fine, but the thing can not be secured (not using that script anyway).
To fix this the suggestion from sreddy works well: make a softlink from where the script would expect the socket to where it actually is. Example:
(I use /tmp/ as a default location for sockets)
It worked for me with the following changes
Whatever path for socket is mentioned in [mysqld] and same in [client] in my.cnf and restart mysql
This might be a stupid suggestion but make 100% sure your DB is still hosted at localhost. For example, if a Network Admin chose (or changed to) Amazon DB hosting, you will need that hostname instead!
I am using the hosting provider 1and1 and got this error after ssh-ing to the host. The fix was simply to provide the host name "mysql -u dbo70123521 -p --host db70313321.db.1and1.com db703133520"
In my case, I was importing a new database, and I wasnt able to connect again after that. Finally I realized that was a space problem.
So you can delete the last database and expand you hard drive or what I did, restored a snapshot of my virtual machine.
Just in case someone thinks that is useful
I came to this issue when i reinstall mariadb with yum, which rename my /etc/my.cnf.d/client.cnf to /etc/my.cnf.d/client.cnf.rpmsave but leave /etc/my.cnf unchanged.
For I has configed mysqld's socket in /etc/my.cnf , and mysql's socket in /etc/my.cnf.d/client.cnf with customized path.
So after the installation, mysql client cannot find the mysql's socket conf, so it try to use the default socket path to connect the msyqld, which will cause this issue.
Here are some steps to locate this isue.
- check if mysqld is running with ps -aef | grep mysqld
- if mysqld is running, show what socket it use with netstat -ln | grep mysql
- check if the socket is mysql client trying to connect. if not, edit /etc/my.conf.d/client.cnf or my.conf to make the socket same with it in mysqld
You also can edit the mysqld's socket, but you need to restart or reload mysqld.
Just rain into the same problem -- and here's how I addressed it.
Assuming mysqld is running, then the problem might just be the mysql client not knowing where to look for the socket file.
The most straightforward way to address this consists in adding the following line to your user's profile .my.cnf file (on linux that's usually under /home/myusername):
If you don't have a .my.cnf file there, then create one containing the following:
In my case, since I moved the mysql default data folder (/var/lib/mysql) in a different location (/data/mysql), I added to .my.cnf the following:
Hope this helps.
ran into this issue while trying to connect mysql in SSH client, found adding the socket path to the command helpful when switching between sockets is necessary.
This is a problem if you are running out of disk space. Solution is to free some space from the HDD.
Please read more to have the explanation :
If you are running MySQL at LINUX check the free space of HDD with the command disk free :
if you are getting something like that :
Then this is the problem and now you have the solution!
Since mysql.sock wants to be created at the mysql folder which is almost always under the root folder could not achieve it because lack of space.
If you are periodicaly give the ls command under the mysql directory (at openSUSE 11.1 is at /var/lib/mysql) you will get something like :
The mysql.sock file appearing and disappearing often (you must to try allot with the ls to hit a instance with the mysql.sock file on folder).
При попытке подключения к серверу MySQL может возникнуть ошибка:
Вариант на другом дистрибутиве (отличается путь до файла mysqld.sock):
Ошибка означает, что не получается подключиться к MySQL серверу через сокет /run/mysqld/mysqld.sock, поскольку данный файл просто не существует.
Эта ошибка может возникнуть при использовании примерно следующей команды:
Причём она одинакова и для MySQL и для MariaDB.
Причина ошибки всегда одна — на хосте, к которому вы пытаетесь подключиться, не работает служба MySQL/MariaDB. Конкретных вариантов может быть множество: от банальных что вы забыли установить службу до более сложных, когда из-за ошибки в команде вы подключаетесь не к тому хосту.
42 Answers 42
If your file my.cnf (usually in the /etc/mysql/ folder) is correctly configured with
you can check if mysql is running with the following command:
try changing your permission to mysql folder. If you are working locally, you can try:
that solved it for me
are you sure you installed mysql as well as mysql server..
For example to install mySql server I'll use yum or apt to install both mysql command line tool and the server:
Enable the MySQL service:
Start the MySQL server:
afterwards set the MySQL root password:
I hope it helps.
I had already installed the client, the command I needed was sudo apt-get install mysql-server then life was good
Isn't the output Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38) from the client? It's the client trying and failing to connect, right? (I think the original question needs editing to clarify that).
A quick workaround that worked for me: try using the local ip address (127.0.0.1) instead of 'localhost' in mysql_connect(). This "forces" php to connect through TCP/IP instead of a unix socket.
It worked. but why? Doesn't MySQL resolve localhost and get 127.0.0.1 anyway before even trying to connect?
I got the following error
Tried several ways and finally solved it through the following way
I had a similar issue; moved from ethernet (192.168.220.11) to wifi (192.168.220.12) but had bind-address hard-coded to ethernet IP. Changing to localhost fixed it.
Make sure you are running mysqld : /etc/init.d/mysql start
I got this error when I set cron job for my file. I changed the permissions of file to 777 but it still not worked for me. Finally I got the solution. May be it will be helpful for others.
Try with this command:
Remember that -h means host, -P means port and -p means password.
Forcing a connection over TCP/IP instead of using a socket is inefficient (and requires that you turn on localhost TCP/IP support in the server, as per this earlier answer). The accepted answer from 2011 is better: Configure the server so you can use a socket properly.
To prevent the problem from occurring, you must perform a graceful shutdown of the server from the command line rather than powering off the server.
This will stop the running services before powering down the machine.
Based on Centos, an additional method for getting it back up again when you run into this problem is to move mysql.sock:
Restarting the service creates a new entry called mqsql.sock
As can be seen by the many answers here, there are lots of problems that can result in this error message when you start the MySQL service. The thing is, MySQL will generally tell you exactly what's wrong, if you just look in the appropriate log file.
For example, on Ubuntu, you should check /var/log/syslog . Since lots of other things might also be logging to this file, you probably want to use grep to look at mysql messages, and tail to look at only the most recent. All together, that might look like:
grep mysql /var/log/syslog | tail -50
Don't blindly make changes to your configuration because someone else said 'This worked for my system.' Figure out what is actually wrong with your system and you'll get a better result much faster.
+1 For taking a step back and pointing out something that many of the other answers fail to even consider - that actually seeing what the application might have reported as a problem is a much better approach than to blindly rush in and make changes which may not even be applicable.
Ah, so it's using the wrong .cnf . That explains it. Now I can stop trying random things and address the actual issue. Thanks.
Another workaround is to edit /etc/my.cnf and include host in the section [client]
And then restarting the mysql service.
This workaround was tested in: Server version: 5.5.25a-log Source distribution
I had the same problem and it has been caused by an update of mysql drivers when mysql server was running. I fixed it just restarting both mysql and apache2:
sudo service mysql stop
sudo service mysql start
sudo service apache2 stop
sudo service apache2 start
In my case, mysql wasn't running. I ran sudo service mysql start after running sudo service mysql status to verify it wasn't running.
try with -h (host) and -P(port):
mysql -h 127.0.0.1 -P 3306 -u root -p
In my case, I was using Centos 5.5. I found that the problem was because the mysql service was stopped some how. So I started mysql service with the command:
So.. silly mistake.
If everything worked just fine and you just started seeing this error, before you do anything else, make sure you're not out of disk space:
If the volume where the mysql.sock is being created is at 100% use, MySql won't be able to create it and this will be the cause of this error. All you need to do is delete something that's not needed, like old log files.
This should serve you just fine. There could be a possibility that you changed some commands that affected the mysql configurations.
or systemctl start mariadb.service in Fedora 22 or RedHat 7. After that it is possible to set root password.
There are many solutions to this problem but for my situation, I just needed to correct the DATE on the machine/server (Ubuntu 16.04 Server).
i) Check the date of your server and correct it.
ii) Run sudo /etc/init.d/mysql restart
That should get it started.
I was getting the error because I was running MAMP and my .sock file was in a different location. I just added a symbolic link where the app thought it should be that pointed to where it actually was and it worked like a charm.
If you are using AWS (Amazon Web Services) Micro version, then it is a memory issue. When I ran
from the terminal it would say
So I tried the following and it would just fail.
Then, I was able to restart mysqld.
I had the same problem on the AWS server "micro" instance and I can confirm that making the swap file DID fix the "ERROR 2002 (HY000): Can't connect to local MySQL server through socket /var/run/mysqld/mysqld.sock' (111)" problem. Thank you @jth_92 !
I also found that this was a permissions problem. I compared the MySQL files to a working install (both on Debian 6 squeeze) and had to make the following ownership changes (where mydatabase is any database(s) you have).
For me - this was simply a case of MySQL taking a long time to load. I have over 100,000 tables in one of my databases and it did eventually start but obviously has to take a long time in this instance.
You might want to chek if the hard disk is full ( df on the console), that's what ultimately triggered this error for me.
you can always start mysql server by specifying the location of the mysql.sock file using the --socket option like
This will work even if the location of socket file in specified in a different location in the my.cnf file.
For those whose any solution did not work, try:
check if my.cnf is present
and make sure you have only one bind-address as follows:
bind-address = 127.0.0.1
If not, that might be the problem, just exit nano and save the file.
and service mysql start
note that if you don't have nano (its a text editor) just install it with apt-get install nano and once in just press Ctrl+X to exit, dont forget to say Y to save and use the same file)
Unfortunately this did not work. This basically just says that only the local machine can access mysql. No remote connections.
Worked for me, I'm using Centos
I had this problem too when trying to start the server, so many of the answers here that just say to start the server didn't work. The first thing you can do is execute the following to see if there are any config errors:
I did have one error that showed up:
A simple grep -HR "innodb-online-alter-log-max-size" /etc/mysql/ showed me exactly what file contained the offending line, so I removed that line from the file.
Then, checking my /var/log/mysql/error.log file I had:
Based on this question the accepted solution wouldn't work because I couldn't even get the server started, so I followed what some of the comments said and deleted my /var/lib/mysql/ib_logfile0 and /var/lib/mysql/ib_logfile1 files.
This allowed the server to start and I was able to connect and execute queries, however checking my error log file it was quickly getting filled up with several tens of thousands of lines like this:
Based on a suggestion from here, to fix this I did a mysqldump and restore of all databases (see the link for several other solutions).
I am getting the following error when I try to connect to mysql:
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Is there a solution for this error? What might be the reason behind it?
Ошибки запрета доступа в MySQL
В MySQL учётная запись (УЗ) определяется именем пользователя и клиентским хостом, с которого пользователь может подключиться. УЗ может также иметь данные для аутентификации (например, пароль).
Причин для запрета доступа может быть много. Одна из них связана с учётными записями MySQL, которые сервер разрешает использовать клиентским программам при подключении. Это означает, что имя пользователя, указанное в соединении, может не иметь прав доступа к базе данных.
В MySQL есть возможность создавать учётные записи, позволяющие пользователям клиентских программ подключаться к серверу и получать доступ к данным. Поэтому при ошибке доступа проверьте разрешение УЗ на подключение к серверу через клиентскую программу.
В консоли вводим команду:
Дать привилегии конкретному пользователю в БД по IP-адресу можно, используя следующие команды:
Ошибки запрещённого доступа могут также возникнуть из-за проблем с подключением к MySQL (см. выше).
Заключение
Итак, основной причиной ошибки «ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2 "No such file or directory")» является незапущенная служба mysqld. Причин того, что указанная служба не запущена может быть множество: от банального факта что служба вообще не установлена, до более серьёзных проблем связанных с переполненностью диска и неправильной настройкой конфигурационных файлов и прав доступа к файлам.
Следовательно, выявите и устраните причину, по которой служба не запущена, а затем запустите службу и ошибка исчезнет.
Слишком много подключений
Эта ошибка означает, что все доступные соединения используются клиентскими программами. Количество соединений (по умолчанию 151) контролируется системной переменной max_connections . Устранить проблему можно, увеличив значение переменной в файле конфигурации /etc/my.cnf .
Служба mysqld не может запуститься так как порт 3306 используется другой программой
По умолчанию служба mysqld использует порт 3306 если этот порт использует другой процесс, то это является препятствием для запуска MySQL и в конечном счёте появляется рассматриваемая ошибка.
Для решения проблемы выясните, какая служба прослушивает порт 3306. Например, это можно сделать командой:
А затем остановите эту служу и удалите её из автозагрузки.
Либо можно использовать альтернативный вариант — настроить службу mysqld прослушивать другой, отличный от дефолтного порта. Но это может повлечь необходимость явно указывать порт в любых приложениях, которые подключаются к СУБД MySQL.
Вместо localhost попробуйте использовать 127.0.0.1
Вместо localhost в примерно такой команде:
Используйте 127.0.0.1:
(также обратите внимание на отсутствие пробела между -p и mypassword)
84 Answers 84
I once had this problem and solved it by installing mysql-server , so make sure that you have installed the mysql-server , not the mysql-client or something else.
That error means the file /var/run/mysqld/mysqld.sock doesn't exists, if you didn't install mysql-server , then the file would not exist. So in that case, install it with
But if the mysql-server is already installed and is running, then you need to check the config files.
In /etc/my.cnf , the socket file config may be /tmp/mysql.sock and in /etc/mysql/my.cnf the socket file config may be /var/run/mysqld/mysqld.sock . So, remove or rename /etc/mysql/my.cnf , let mysql use /etc/my.cnf , then the problem may solved.
If I had to explain technically , I would say 1)If you are running "mysql -u
This can also occur if you try to change the directory where the database is stored, but imput the wrong directory in the configuration file (like a typo). Instead of telling you the typo directory does not exist, it will tell you that you lack permission to access it.
As a first step I would recommend an attempt to restart the server process (see other's distinctions of server v.s client). Try sudo /etc/init.d/mysql restart. Usually, re-installation isn't necessary. I would recommend you to first check the log files. Not just mysql's log file but also /var/log/syslog since you may have had a server crash causing mysql to break down as a side effect.
for me it was in etc/mysql/mysql.conf.d/mysqld.cnf . It was the only file where /var/run/mysqld/mysqld.sock was present
Also (to see if it's running):
Probably it is just a misconfiguration in the my.cnf file, in /etc/somewhere (depending on the Linux distribution).
I'm getting the same error. And I've checked and the default bind in both the main and my.cnf is set to 127.0.0.1 already. However using your command above allowed me to connect. Will have to keep hunting to see why just doing "mysql" is giving the error.
I get telnet: Unable to connect to remote host: Connection refused as a result of telnet command. However apache still runs as I'm able to open localhost
Note: mysql -h localhost does not work. Make sure to use mysql -h 127.0.0.1 as specified in the answer.
I am seeing all these answers, but none offer the option to reset the password and no accepted answer. The actual question being he forgot his password, so he needs to reset, not see if it's running or not (installed or not) as most of these answers imply.
Не удаётся подключиться к серверу MySQL
Ещё одна похожая и часто встречающаяся ошибка подключения — «(2003) Can’t connect to MySQL server on ‘server’ (10061)». Это означает, что в сетевом соединении было отказано.
Следует проверить, работает ли в системе сервер MySQL (смотрите выше) и на тот ли порт вы подключаетесь (как найти порт, можно посмотреть выше).
Похожие частые ошибки, с которыми вы можете столкнуться при попытке подключиться к серверу MySQL:
Перезапустите службу mysqld
Попробуйте просто перезапустить службу командой:
Либо следующим образом, значала узнайте PID (идентификатор) процесса mysql:
Затем выполните следующую команду, в которой вместо [PID] укажите число, полученное из предыдущей команды:
Затем вновь запустите службу:
Неверно указан хост для подключения
Для указания удалённого хоста используется опция -h. Из-за привычки указывать хост после имени пользователя через знак @ (как это делается, например, для SSH), либо указывать удалённый хост без опции -h, команда может оказаться неверной в том плане, что вместо подключения к удалённому хосту, вы пытаетесь подключиться, например, к своей собственной системе, на которой служба MySQL не установлена.
Следовательно, отредактируйте команду, используйте опцию -h или более длинный вариант --host=имя_хоста для указания хоста, к которому вы хотите подключиться.
Кстати, для указания имени пользователя используется опция -u. Если пароль отличается от стандартного, то используется опция -P (заглавная буква). Опция -p (прописная буква) используется для указания базы данных, которая выбирается для использования.
Служба mysqld по умолчанию не добавляется в автозагрузку на некоторых дистрибутивах
Помните, что на некоторых дистрибутивах (например, производных Arch Linux, на Kali Linux) даже после установки MySQL или MariaDB они не добавляются в автозагрузку и не запускаются по умолчанию.
Для запуска службы и её авто старта при последующих включениях компьютера выполните команды:
Неправильные права на файл /run/mysqld/mysqld.sock
У MySQL/MariaDB должно быть достаточно прав для создания и записи в файл /run/mysqld/mysqld.sock (или /var/run/mysqld/mysqld.sock). Можно попробовать решить проблему следующим образом, если файл /run/mysqld/mysqld.sock (или /var/run/mysqld/mysqld.sock - указывайте файл в соответствии с вашими настройками в my.cnf) не существует, то создайте его:
Затем сделайте пользователя mysql владельцем этого файла:
Установите правильные права на этот файл:
Вновь попробуйте запустить сервис:
Проблемы запуска службы из-за несовместимой настройки apparmor
Если при запуске службы вы получаете ошибку и вы используете профили apparmor, проверьте, чтобы профиль apparmor позволял процессу mysqld иметь доступ в необходимую для него директорию.
Несовместимость может быть вызвана, к примеру, файл сокета для MySQL настроен на сохранение по пути /run/mysqld/mysqld.sock, но в профиле apparmor дано разрешение на /var/run/mysqld/mysqld.sock
Чтобы убедиться, что дело именно в apparmor, попробуйте отключить его:
Если проблема исчезла и служба mysqld запустилась, значит нужно поверить разрешения для mysqld и добавить необходимые пути.
К примеру для показанного примера решением проблемы является добавление в /etc/apparmor.d/usr.sbin.mysqld строк:
Потеря соединения с сервером MySQL
С этой ошибкой можно столкнуться по одной из следующих причин:
- плохое сетевое соединение;
- истекло время ожидания соединения;
- размер BLOB больше, чем max_allowed_packet .
В первом случае убедитесь, что у вас стабильное сетевое подключение (особенно, если подключаетесь удалённо).
Если проблема с тайм-аутом соединения (особенно при первоначальном соединении MySQL с сервером), увеличьте значение параметра connect_timeout .
В случае с размером BLOB нужно установить более высокое значение для max_allowed_packet в файле конфигурации /etc/my.cnf в разделах [mysqld] или [client] как показано ниже.
Если файл конфигурации недоступен, это значение можно установить с помощью следующей команды.
Убедитесь, что служба MySQL/MariaDB настроена правильно
Если причина проблемы оказалась в том, что служба не запущена и после попытки запуска служба вновь оказалась неактивной, значит проблема может быть в неправильной настройке сервера MySQL/MariaDB.
Файлы конфигурации (настроек) MySQL и MariaDB могут размещаться в разных директориях, например:
- /etc/my.cnf
- /etc/mysql/my.cnf
- /var/lib/mysql/my.cnf
При этом в файлах могут быть установлены различные значения одной и той же настройки, что приводит к проблеме. Устраните противоречие, либо удалите или переименуйте один из файлов и попробуйте вновь запустить службу.
На что стоит обратить внимание в конфигурационных файлах
Если вы хотите сохранить оба конфигурационных файла, то проверьте, чтобы значение socket было одинаковым. Также для bind-address должен быть установлен правильный IP адрес. Если к этому серверу подключаются только приложения, которые запущены на этом же сервере, то в качестве значения bind-address нужно прописать localhost или 127.0.0.1
Читайте также: