You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker Compose中Flask应用无法连接MySQL容器的问题求助

解决Docker Compose中Flask应用无法连接MySQL容器的问题

核心问题定位

错误根源是容器间通信端口使用错误:在Docker Compose同一网络中,容器通过服务名互相访问时,必须使用容器内部的端口,而非主机映射的端口。你的MySQL容器内部端口为3306,主机映射到3307,但Flask应用连接时误用了mysql:3307,导致连接失败。

解决方案步骤

1. 修正数据库连接配置

修改dbService.py中的数据库配置,将端口改为MySQL容器内部默认的3306:

config = {
    'host': 'mysql',  # 匹配Docker Compose中的服务名,配置正确
    'port': '3306',   # 替换为主机映射的3307,改为容器内部端口
    'user': 'user',
    'password': 'password',
    'database': 'db',
}

2. 修复Docker Compose卷配置

你的docker-compose.yml中卷配置存在多余空格,可能导致挂载异常,修正为:

volumes:
  - /mysql_data:/var/lib/mysql  # 去掉路径间的空格

3. 替换固定Sleep为智能重试(推荐)

time.sleep(10)无法保证MySQL服务完全就绪,建议在连接逻辑中添加重试机制,替代硬编码延迟:

import mysql.connector
from mysql.connector import Error
import time

def create_tables():
    logger.info("Entering create tables method from dbservice")
    max_retries = 5
    retry_delay = 3
    for attempt in range(max_retries):
        try:
            connection = mysql.connector.connect(**config)
            if connection.is_connected():
                cursor = connection.cursor()
                # 检查并创建表逻辑
                cursor.execute("SHOW TABLES LIKE 'emails'")
                table_exists = cursor.fetchone()
                if not table_exists:
                    cursor.execute(
                        '''
                        CREATE TABLE emails (
                        id INT PRIMARY KEY AUTO_INCREMENT,
                        created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                        email VARCHAR(255) NOT NULL,
                        verified BOOLEAN NOT NULL,
                        flatType VARCHAR(255) NOT NULL,
                        streetName VARCHAR(255) NOT NULL,
                        blkFrom INT NOT NULL,
                        blkTo INT NOT NULL,
                        lastSent TIMESTAMP,
                        token VARCHAR(255))
                        ''')
                    connection.commit()
                connection.close()
                logger.info("Tables created successfully or already exist")
                return
        except Error as e:
            logger.warning(f"Connection attempt {attempt+1} failed: {e}")
            time.sleep(retry_delay)
    logger.error("Failed to connect to MySQL after maximum retries")

验证修改

重新构建并启动容器:

docker-compose build --no-cache && docker-compose up

此时Flask应用应能正常连接到MySQL容器。

内容的提问来源于stack exchange,提问作者Randy Chng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 12:50:54