0

The connection is not succeeding in docker. Look at my settings:

Dockerfile

FROM python:3.8.5-alpine

WORKDIR /app

COPY requirements.txt .

RUN python3 -m pip install --upgrade pip

RUN pip install -r requirements.txt

COPY . .

CMD ["python3", "-m", "scraper"]

docker-compose.yml

   version: '3'
    services:
      python_app:
        build:
          context: .
          dockerfile: Dockerfile
        ports:
          - '80:80'
        links:
          - 'mysql_db'
        depends_on:
          - mysql_db
        networks:
          - app-tier
    
      mysql_db:
        image: mysql:5.7
        ports:
          - '3307:3306'
        environment: 
          MYSQL_ROOT_PASSWORD: 'flavio'
          MYSQL_DATABASE: 'Vestibular'
          MYSQL_USER: 'flavio'
          MYSQL_PASSWORD: ''
        networks:
          - app-tier
    
    networks:
      app-tier:
        driver: bridge

db.py

import mysql.connector

def insert_into_database(data):
    print("Salvando no banco de dados")
    aux = ""
    for i, item in enumerate(data):
        if i == len(data)-1:
            aux += str(item)
        else:
            aux += f"{str(item)}, "

    
    try:
        connection = mysql.connector.connect(host='localhost',
                                            database='Vestibular',
                                            user='flavio',
                                            password='')
        cursor = connection.cursor()

        stmt = "SHOW TABLES LIKE 'Candidates'"
        cursor.execute(stmt)
        result = cursor.fetchone()

        mySql_Create_Table_Query = """CREATE TABLE Candidates ( 
                             Id int(11) AUTO_INCREMENT NOT NULL,
                             Name varchar(250) NOT NULL,
                             Score varchar(250) NOT NULL,
                             PRIMARY KEY (Id)) """
        

        mySql_insert_query = f"""INSERT INTO Candidates (Name, Score) 
                            VALUES 
                            {aux}; """

        if not result:
            cursor.execute(mySql_Create_Table_Query)
        cursor.execute(mySql_insert_query)
        connection.commit()
        print(cursor.rowcount, "Record inserted successfully into Candidates table")
        cursor.close()

    except mysql.connector.Error as error:
        print("Failed to insert record into Candidates table {}".format(error))

    finally:
        if connection.is_connected():
            connection.close()
            print("MySQL connection is closed")

1 Answer 1

1

The python_app and mysql_db services/containers do not share a network namespace, thus they don't have the same localhost. Just use mysql_db as the hostname when connecting to the DB.

I would recommend that your python code takes the DB hostname from an env var or command line argument. If you want to hardcode it, you can use something like db and then use the docker compose links aliasing feature which is documented here to map db to the actual service name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.