Search code examples
pythonmysqlbashdockerdocker-compose

How to start my Mysql database to connect to my api


I am trying to make a mysql database to connect to my api (the two of them are for a local infrastructure).

right now i tried to make my api check my production database (which is working on port 3306), but when i try without my production docker system working, it fails. here are my scripts:

My docker-compose:

version: '3.0'

services:
  database:
    build:
      context: ./
      dockerfile: ./project/docker/DockerfileDB
    image: tp5_ima_db_ltn_ad
    environment:
      MYSQL_ROOT_PASSWORD: "root"
    ports:
      - 3306:3306
  api:
    build:
      context: ./
      dockerfile: ./project/docker/DockerfileAPI
    image: tp5_ima_api_ltn_ad
    environment:
      INFRA_TP5_DB_TYPE: "MYSQL"
      INFRA_TP5_DB_HOST: "database"
      INFRA_TP5_DB_PORT: 3306
      INFRA_TP5_DB_USER: "root"
      INFRA_TP5_DB_PASSWORD: "root"
    volumes:
      - .:/mnt/app
    ports:
      - 15555:5555
    depends_on:
      - database

My DockerfileDB :

FROM mysql:5.7

COPY ./project/scripts/db/init.sql /docker-entrypoint-initdb.d/

(the copy line needs to be here to copy my env variable in the local machine)

My error in details:

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

Traceback (most recent call last)
File "/usr/local/lib/python3.8/dist-packages/mysql/connector/network.py", line 509, in open_connection
self.sock.connect(sockaddr)
During handling of the above exception, another exception occurred:
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1498, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1476, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1473, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 882, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 880, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 865, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]
File "/mnt/app/project/main/api.py", line 16, in route_getUsers
return make_response(jsonify({'msg': dom.getUsers()}))
File "/mnt/app/project/main/domain.py", line 12, in getUsers
return {"InitialUsers": db.getInitialUsersFromDB(), "NewUsers": db.getNewUsersFromDB()}
File "/mnt/app/project/main/db.py", line 15, in getInitialUsersFromDB
return getDB().getUsersOfType(1)
File "/mnt/app/project/main/MYSQLDB.py", line 34, in getUsersOfType
conn = mysql.connector.connect(**getConfig())
File "/usr/local/lib/python3.8/dist-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/mysql/connector/connection.py", line 95, in __init__
self.connect(**kwargs)
File "/usr/local/lib/python3.8/dist-packages/mysql/connector/abstracts.py", line 716, in connect
self._open_connection()
File "/usr/local/lib/python3.8/dist-packages/mysql/connector/connection.py", line 206, in _open_connection
self._socket.open_connection()
File "/usr/local/lib/python3.8/dist-packages/mysql/connector/network.py", line 511, in open_connection
raise errors.InterfaceError(
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'database:3306' (111 Connection refused)
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object

and just for good mesure, here is my DockerfileAPI :

#! /bin/bash
# From image
FROM demers/python420w4a

# Copy requirements
COPY ./requirements.txt ./

# Install requirements
RUN pip3 install -r ./requirements.txt

# Set the working directory in the container
WORKDIR /mnt/app/

# Command to run the APP
CMD ["./run.sh", "./project/main/api.py", "5555"]`

Important note: this is a school project, so my mysql database needs to be in version 5.7.


Solution

  • You can add a healthcheck to the DB container and then use service_healthy as the condition

    version: '3.0'
    
    services:
      database:
        build:
          context: ./
          dockerfile: ./project/docker/DockerfileDB
        image: tp5_ima_db_ltn_ad
        environment:
          MYSQL_ROOT_PASSWORD: "root"
        ports:
          - 3306:3306
        healthcheck:
           test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      api:
        build:
          context: ./
          dockerfile: ./project/docker/DockerfileAPI
        image: tp5_ima_api_ltn_ad
        environment:
          INFRA_TP5_DB_TYPE: "MYSQL"
          INFRA_TP5_DB_HOST: "database"
          INFRA_TP5_DB_PORT: 3306
          INFRA_TP5_DB_USER: "root"
          INFRA_TP5_DB_PASSWORD: "root"
        volumes:
          - .:/mnt/app
        ports:
          - 15555:5555
        depends_on:
          database:
             condition: service_healthy