0

I am starting a Flask project and I want to run unit tests in PyCharm using Docker remote interpreter, but I am not being able to connect to the mysql database container when running the tests. The application runs normally, so the database is reachable outside the container. In the past I managed to do that in PhpStorm, but the configurations in PyCharm are not the same and I am having some trouble setting everything up. I already managed to use the remote interpreter to run tests, but the only trouble is when I need to connect to the database.

I am getting the following error when trying to connect:

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (111 Connection refused)

So, the server is reachable, but for whatever reason it is not allowing to connect.

Here is the docker-compose.yml

version: "2"

networks:
    learning_flask:
      name: learning_flask
      driver: bridge

services:
  mysql:
    image: mysql:5.7
    container_name: mysql
    restart: unless-stopped
    tty: true
    ports:
      - "127.0.0.1:3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - ./db:/docker-entrypoint-initdb.d/:ro
    networks:
      - learning_flask

  app:
    build: ./app
    container_name: learning_flask_app
    ports:
      - "5000:5000"
    volumes:
      [ './app:/app' ]
    depends_on:
      - mysql
    networks:
      - learning_flask

and then the code I am trying to execute:

import unittest
import mysql.connector

class TestCase(unittest.TestCase):

    def test_something(self):
        config = {
            'user': 'root',
            'password': 'root',
            'host': 'localhost',
            'port': '3306'
        }
        connection = mysql.connector.connect(**config)


if __name__ == '__main__':
    unittest.main()

If I try to change the host on the connection config to mysql, I get the following error:

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'mysql:3306' (-2 Name or service not known)
Luiz Agner
  • 77
  • 10
  • Have you tried using `3306:3306` instead of `127.0.0.1:3306:3306` in the docker compose config for mysql service? – Prathisrihas Reddy Jan 01 '21 at 00:15
  • @PrathisrihasReddy yeah... just tried that and I'm still receiving the same error – Luiz Agner Jan 01 '21 at 04:23
  • Does this [answer](https://stackoverflow.com/a/42107365/6505847) help? or can you also check [this](https://stackoverflow.com/a/42031017/6505847) – AzyCrw4282 Jan 01 '21 at 09:18
  • @AzyCrw4282 unfortunately this also didn't help... I have no idea what is happening. If I enter the `app` container I'm able to ping `mysql` container, but when it comes to running the tests it just won't work – Luiz Agner Jan 01 '21 at 18:15

0 Answers0