简体   繁体   中英

Cannot connect to MySQL from python on docker-compose

I'm trying to build a docker-compose for my flask-app running with mysql. The problem is: my flask cannot access to mysql (both in docker-compose) and keeps returning this problem: pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 111] Connection refused)") .

So I decided to write a simple flask app and copy the connection to mysql over. The Flask app on docker-compose works fine alone and mysql also works fine because I can write query in dbeaver. But it will raise error when ever I tried to connect to mysql in the script: connection = pymysql.connect(host='127.0.0.1') with the similar error I mentioned above

The code will break immediately when it hits host=127.0.0.1 .

Here is my app.py:

from flask import Flask
import pymysql

app = Flask(__name__)
    
@app.route('/')
def index():
    return '<h1>Login</h1>'
    
if __name__ == '__main__':
    connection = pymysql.connect(host='127.0.0.1',
                                 user='root',
                                 password='password',
                                 port=33061,
                                 cursorclass=pymysql.cursors.DictCursor)
    cur = connection.cursor()
    cur.execute(''' SELECT * FROM data_warehouse.ofactory_results''')
    order_no = cur.fetchone()
    print(order_no)
    
    print('STARTTTTTTT!')
    app.run(debug=True)

Here is my docker-compose:

version: "3.9"
    
services:
  app:
    build:
      context: .
    ports:
      - 5000:5000
    
  mysql_db:
    container_name: mysql_db
    image: mariadb:latest
    restart: always
    ports:
      - "0.0.0.0:33061:3306"
    environment: 
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=data_warehouse
      - MYSQL_USER=debezium
          - MYSQL_PASSWORD=debezium
     volumes:
       - ./mysql:/var/lib/mysql
       - ./mysql/my.cnf:/etc/mysql/my.cnf

Here is my dockerfile:

FROM python:3.9
COPY requirements.txt .     
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]

Here is the error:

Traceback (most recent call last):
prep-app-1  |   File "/usr/local/lib/python3.9/site-packages/pymysql/connections.py", line 613, in connect
prep-app-1  |     sock = socket.create_connection(
prep-app-1  |   File "/usr/local/lib/python3.9/socket.py", line 844, in create_connection
prep-app-1  |     raise err
prep-app-1  |   File "/usr/local/lib/python3.9/socket.py", line 832, in create_connection
prep-app-1  |     sock.connect(sa)
prep-app-1  | ConnectionRefusedError: [Errno 111] Connection refused
prep-app-1  | 
prep-app-1  | During handling of the above exception, another exception occurred:
prep-app-1  | 
prep-app-1  | Traceback (most recent call last):
prep-app-1  |   File "//app.py", line 10, in <module>
prep-app-1  |     connection = pymysql.connect(host='127.0.0.1',
prep-app-1  |   File "/usr/local/lib/python3.9/site-packages/pymysql/connections.py", line 353, in __init__
prep-app-1  |     self.connect()
prep-app-1  |   File "/usr/local/lib/python3.9/site-packages/pymysql/connections.py", line 664, in connect
prep-app-1  |     raise exc
prep-app-1  | pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 111] Connection refused)")
prep-app-1 exited with code 1

localhost inside your docker container != localhost of your host machine.

You may use:

connection = pymysql.connect(host='mysql_db',
                             user='root',
                             password='password',
                             port=3306,
                             cursorclass=pymysql.cursors.DictCursor)

Note mysql_db which is name of your db service. Docker, internally will resolve that name into container ip address in docker network.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM