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:
- Make sure the MySQL container is running by using the
docker pscommand. If it is not running, start it withdocker start <container_name> - 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. - 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.
- 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.
- Check your mysql container IP using
docker inspect <container_name>command. You can also check the network usingdocker network lscommand. - 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-mysqlIn 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.