Skip to content

Connecting PHP to a MySQL inside a Docker container

If you ever had connection problems between PHP and a MySQL database in a Docker container, this article is for you.

I just went though this setting up this site. My linux box on AWS runs a couple of Node.js websites and I just wanted to install this WordPress site on the same server. I already had a Nginx server acting as a proxy and a MySQL server running on the server inside a Docker container so it would be very simple install php-fpm and configure another website on Nginx and use the same db server to kick off a WordPress site.

I installed php-fpm and some other PHP modules on the box, set up a new database, a new user, tested the connection on the console and it was all fine but when I tried to connect to MySQL database from my WordPress site, there was an error.

My WordPress website simply didn’t connect with the database, although I was able to connect to the db from all kinds of places, that was really weird.

WordPress error messages are not that clear, so I had the awesome idea to create a little script on the root of my webserver so I could see the error message for the connection attempt.

That’s what I came up with:

define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASSWORD', 'myPasswordHere');
define('DB_NAME', 'myDBNameHere');

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if (!$link) {
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
echo "<html><head><title>Connection Failed!</title></head><body>
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;

echo "<html><head><title>Connection Successfull</title></head><body>
echo "Success: A proper connection to MySQL was made!" . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

When I ran the script, I got this message:

Warning: mysql_connect(): 
[2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock)

If you check the PHP documentation you’ll find that whenever you specify “localhost” or “localhost:port” as server on mysql_connect, the MySQL client library will override this and try to connect to a local socket. Since the MySQL server is inside a container, php-fpm can’t find the socket file, hence the file not found message. Here’s the PHP documentation if you want to check it out.

A quick workaround to use TCP/IP instead of socket is to configure your connection using “” instead of “localhost”.

Turned out to be very easy to fix this issue, and it was a good opportunity to learn that when your PHP connection is set to ‘localhost’, it uses sockets instead of TCP/IP to connect to the database.

Leave a Reply