W3docs

Docker MYSQL '[2002] Connection refused'

The '[2002] Connection refused' error in Docker when trying to connect to a MySQL container typically indicates that the MySQL server is not running or is not accessible on the network.

The [2002] Connection refused error in Docker when trying to connect to a MySQL container typically indicates that the MySQL server is not running or is not accessible on the network. Here are a few things to check if you encounter this error:

  1. Make sure the MySQL container is running by using the docker ps command. If it is not running, start it with docker start <container_name>
  2. Check that the MySQL service is running inside the container by running docker exec -it <container_name> mysql -u root -p. It will prompt for the password then you can check the service status.
  3. Verify that the host and port specified in your application's configuration are correct. By default, MySQL listens on port 3306, so make sure your application is configured to connect to that port.
  4. If you are running the MySQL container and your application on different hosts or in different networks, make sure that the host specified in your application's configuration is reachable from the application.
  5. Check your mysql container IP using docker inspect <container_name> command. You can also check the network using docker network ls command.
  6. Check container logs for startup failures using docker logs <container_name>.

Example:

Command example of connecting a docker container to the MySQL server

docker network create my-network
docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d --network my-network mysql:8.0
docker run --name some-app -d --network my-network app-that-uses-mysql

In the above example, the some-app container can connect to the MySQL server using the hostname some-mysql and the default MySQL port (3306), and it will authenticate using the root user and the password specified in the MYSQL_ROOT_PASSWORD environment variable.

Note: In the above example command, mysql:8.0 specifies the MySQL version to use.