Step by step, Debug and fix PHP Mongodb error "No suitable servers found". This tutorial works with pure php and also popular php frameworks today such as: Laravel, Yii, CodeIgniter ...
Raw Error:
No suitable servers found (`serverSelectionTryOnce` set):
[connection refused calling ismaster on 'localhost:27017']
[connection refused calling ismaster on '127.0.0.1:27017']
Debug Step by Step !
1. Check if mongodb is working or not:
netstat -tulpn | grep LISTEN
Please check if the mongodb process is working or not, the correct port or not. If the mongodb server is not working properly please resolve that issue.
2. Check that the php-mongodb extension is installed correctly (Unrelated, but I think it is useful)
Create a php file with content:
<?php
phpinfo();
?>
3. Can you connect to the mongodb server via the Command line (CLI)?
mongo
4. Check SELinux Permission (Very important)
If you've debugged through steps 1 - 3 and haven't found the problem yet, SELinux is probably the problem that caused your error.
For added security, SELinux is enabled by default on newer server versions. By default SELinux will not allow apache, PHP is automatically opened to the new socket to connect out (or local). Meanwhile, php-mongodb ext needs to initialize the socket to connect to the mongodb server. So you will encounter the error as seen.
To fix this issue grant SELinux permission to apache to freely open the socket.
setsebool -P httpd_can_network_connect 1
Note: Some other php libraries that use sockets may have similar problems with SELinux, for example: php-redis, curl ...
Done !