简体   繁体   中英

mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

I am creating a docker file that contains a flask app and mysql. This should run on localhost for now.

The flask app is running and so as the mysql server. I am able to connect to mysql server. The app is not able to connect to db.

Python code connecting

def establish_connection():
    config = {
        'user': 'root',
        'password': 'root',
        'host': '127.0.0.1',
        'port': '3306',
        'database': 'persist'
    }

    cnx: str = mysql.connector.connect(**config)
    print(cnx)
    return cnx

Dockerfile

FROM python:3.7.4-buster
WORKDIR /stocksite
ENV FLASK_APP main.py
ENV FLASK_RUN_HOST 0.0.0.0
EXPOSE 5000 32000 3306
COPY . .
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["flask", "run"]

docker-compose.yml

version: '3'
services:
  web:
    build: .
    ports:
      - "5000:5000"

  db:
    image: mysql
    container_name: db
    ports:
      - "32000:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - ./data/db:/docker-entrypoint-initdb.d

I receive the below error:

mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

Docker compose services are available to other services using their name. Your db service can be connected to from your web container using db:3306

config = {
    'user': 'root',
    'password': 'root',
    'host': 'db',
    'port': '3306',
    'database': 'persist'
}

In the docker-compose you map the port 3306 of the db inside the container to the port 32000 on the host machine.

In the app you should use port 32000 not 3306 .

def establish_connection():
config = {
    'user': 'root',
    'password': 'root',
    'host': '127.0.0.1',
    'port': '32000',
    'database': 'persist'
}

cnx: str = mysql.connector.connect(**config)
print(cnx)
return cnx

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