(pymysql.err.OperationalError)(2003,“无法在'0.0.0.0'上连接到MySQL服务器([Errno 111]连接被拒绝)”)

我尝试将烧瓶sqlalchemy容器与mysql容器连接。并配置它们之间的连接。 我有initdb python,可在我的项目中创建所有表:

from model import Base

engine = create_engine('mysql+pymysql://test:test@0.0.0.0/test')

Base.metadata.create_all(engine)

和我的码头工人组成:

version: '3'

services:
  flask:
    build: ./flask
    container_name: flask
    restart: always
    depends_on:
      - db
    links:
      - db
    volumes:
      - ./flask:/flask
    depends_on:
      - db
    ports:
      - 5000:5000

  db:
    image: mysql
    container_name: mysql_db
    environment:
      - MYSQL_USER=test
      - MYSQL_ROOT_PASSWORD=test
      - MYSQL_PASSWORD=test
      - MYSQL_DATABASE=test
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    volumes:
      - ./db:/docker-entrypoint-initdb.d
    restart: always
    ports:
      - 3308:3308

当我尝试使用sqlalchemy将数据保存在我的数据库中时,收到错误消息:

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '0.0.0.0' ([Errno 111] Connection refused)")

我尝试为数据库添加sql文件,但无济于事。当我打开数据库容器时,测试数据库不存在。

评论
ut_sed
ut_sed

0.0.0.0 is the bind-all address, you can't connect to it. Try 127.0.0.1 or the actual IP of the machine if this is a remote server, or is on a VM or container.

点赞
评论
等待出嫁
等待出嫁

In this docker-compose environment, the flask container can reach the db container at dns db but not 0.0.0.0.

因此,您必须将代码更新为如下形式

from model import Base

engine = create_engine('mysql+pymysql://test:test@db/test')

Base.metadata.create_all(engine)
点赞
评论