<p>The <code>python_app</code> and <code>mysql_db</code> services/containers do not share a network namespace, thus they don't have the same <code>localhost</code>. Just use <code>mysql_db</code> as the hostname when connecting to the DB.</p>
<p>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 <code>db</code> and then use the docker compose links aliasing feature which is documented <a href="https://docs.docker.com/compose/networking/#links" rel="nofollow noreferrer">here</a> to map <code>db</code> to the actual service name.</p>

CC BY-SA 4.0
2022-01-25T14:04:53.563Z
2022-01-25T14:33:56.070Z
2022-01-25T14:33:56.070Z
vaizki
<p>The connection is not succeeding in docker. Look at my settings:</p>
<p>Dockerfile</p>
<pre><code>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 [&quot;python3&quot;, &quot;-m&quot;, &quot;scraper&quot;]
</code></pre>
<p>docker-compose.yml</p>
<pre><code>   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
</code></pre>
<p>db.py</p>
<pre><code>import mysql.connector

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

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

        stmt = &quot;SHOW TABLES LIKE 'Candidates'&quot;
        cursor.execute(stmt)
        result = cursor.fetchone()

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

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

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

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

    finally:
        if connection.is_connected():
            connection.close()
            print(&quot;MySQL connection is closed&quot;)
</code></pre>

<docker><docker-compose><dockerfile><python><mysql>
My Python application doesn't communicate with MySQL inside docker. Can someone help me?
Flavio W.
# My Python application doesn't communicate with MySQL inside docker. Can someone help me?

(Asked by: username_0 on 2022-01-25)

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")

**Tags:** docker, docker-compose, dockerfile, python, mysql


---

## 1 answers

### Answer by username_1 on 2022-01-25. Score: 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](https://docs.docker.com/compose/networking/#links) to map `db` to the actual service name.


---

