简体   繁体   中英

Cannot connect to MYSQL using SQLAlchemy

I am not able to connect to my mysql. I am using pymysql for connecting to Mysql.

Here is my code in Flask:

app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://"+config.get_config("MYSQL_DATABASE_USER")+":"\
                                        + config.get_config("MYSQL_DATABASE_PASSWORD")+"@"\
                                        + config.get_config("SERVER_HOST_NAME")+":"\
                                        + config.get_config("MYSQL_DATABASE_PORT")+"/"\
                                        + config.get_config("MYSQL_DATABASE_DB")

And this is my docker-compose file

version: "3"
services:
  db:
    build: ./db
    restart: always
    ports:
      - "3308:3306"
    environment:
      - MYSQL_USER=root
      - MYSQL_ROOT_PASSWORD=root@123
  flask:
    build: ./python-backend
    links:
      - db
    depends_on:
      - db
    ports: 
      - "7000:7000"
  angular:
    build: ./angular-template
    depends_on:
      - flask
    ports:
      - "4200:4200"

When I am hitting a route this says

"(pymysql.err.OperationalError) (2003, \"Can't connect to MySQL server on '0.0.0.0' ([Errno 111] Connection refused)\")\n(Background on this error at: http://sqlalche.me/e/e3q8)"

Any clue on what I am doing wrong here?

And here is my config file

"SERVER_SECRET":"winter is coming",
            "MYSQL_DATABASE_USER": "root",
            "MYSQL_DATABASE_PASSWORD": "root@123",
            "MYSQL_DATABASE_DB": "template",
            "MYSQL_DATABASE_HOST": "172.17.0.1", #localhost
            "MYSQL_DATABASE_CHARSET": "utf-8",
            "MYSQL_DATABASE_PORT": "3306",
            "SERVER_HOST_NAME": "0.0.0.0", #localhost
            "SERVER_PORT": 7000,
            "SERVER_DEBUG": True

Change DB host name in your config file -

"MYSQL_DATABASE_HOST": "db", #docker compose service name

Seems like you are using SERVER_HOST_NAME to repesent DB host, change below -

"SERVER_HOST_NAME": "db", #docker compose service name

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