Indie Heaven
Why Can't I Connect to Mysql from Docker ?


Adventures in Node.JS - Part 3

Connecting to MySql

The simple and quick answer is, "don't use localhost". Instead, use the name of the container.

There are dozens of questions about this on StackOverflow, it's a common issue.

Typically, a MySql container inside Docker is started this way:

docker run --name mysql -d -e MYSQL_ALLOW_EMPTY_PASSWORD=TRUE --expose 3306
        --mount type=bind,source=/e/databases,target=/var/lib/mysql mysql


This command maintains a permanent data store using a bind mount, which is thoroughly covered in the Docker documentation. And the environment variable is configured to allow password-less login as root. However note the container name. It is 'mysql', not localhost. Docker doesn't necessarily know what localhost is. But it knows the names of its containers. Therefore, we set up our connection parameters as follows:

exports.dbhost = "mysql";
exports.dbuser = "root";
exports.dbpass = "";
exports.dbname = "db";
exports.dbport = 3306;


This will allow Docker to locate the database by container name.

Note that port 3306 is exposed so other containers can find it.

An app connecting to the mysql container can connect this way :

docker run --name myapp -d --link mysql:db --mount type=bind,source=/e/myapp,target=/var/www/html -p 8080:80 myapp

The above command also uses a bind mount, this way HTML pages can be replaced into a running container in real time.


Back to the Console

Back to the Home Page


(c) 2024 Indie Heaven LLC
All Rights Reserved
webmaster@indieheaven.io