我试图连接mysql容器与我的python flask应用程序,我在运行docker-compose build --no-cache && docker-compose up时出现此错误:

Creating network "hdbresalepricealert_sql_network" with the default driver
Creating hdbresalepricealert_mysql_1 ... done
Creating hdbresalepricealert_python_app_1 ... done
Attaching to hdbresalepricealert_mysql_1, hdbresalepricealert_python_app_1
mysql_1       | 2023-12-22 04:48:45+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.2.0-1.el8 started.
mysql_1       | 2023-12-22 04:48:46+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
mysql_1       | 2023-12-22 04:48:46+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.2.0-1.el8 started.
mysql_1       | '/var/lib/mysql/mysql.sock' -> '/var/run/mysqld/mysqld.sock'  
mysql_1       | 2023-12-22T04:48:46.269421Z 0 [System] [MY-015015] [Server] MySQL Server - start.
mysql_1       | 2023-12-22T04:48:46.860627Z 0 [Warning] [MY-011068] [Server] The syntax '--skip-host-cache' is deprecated and will be removed in a future release. Please use SET GLOBAL host_cache_size=0 instead.
mysql_1       | 2023-12-22T04:48:46.866169Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.2.0) starting as process 1
mysql_1       | 2023-12-22T04:48:46.891660Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
mysql_1       | 2023-12-22T04:48:47.157634Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
mysql_1       | 2023-12-22T04:48:47.482067Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
mysql_1       | 2023-12-22T04:48:47.482195Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
mysql_1       | 2023-12-22T04:48:47.485815Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.        
mysql_1       | 2023-12-22T04:48:47.512210Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
mysql_1       | 2023-12-22T04:48:47.512345Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.2.0'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
python_app_1  | INFO:services.dbService:Entering create tables method from dbservice
python_app_1  | ERROR:services.dbService:Unable to create tables due to 2003 (HY000): Can't connect to MySQL server on 'mysql:3307' (111)
python_app_1  |  * Serving Flask app 'app'
python_app_1  |  * Debug mode: on
python_app_1  | INFO:werkzeug:WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.        
python_app_1  |  * Running on all addresses (0.0.0.0)
python_app_1  |  * Running on http://127.0.0.1:5000
python_app_1  |  * Running on http://172.22.0.3:5000
python_app_1  | INFO:werkzeug:Press CTRL+C to quit
python_app_1  | INFO:werkzeug: * Restarting with stat
python_app_1  | INFO:services.dbService:Entering create tables method from dbservice
python_app_1  | ERROR:services.dbService:Unable to create tables due to 2003 (HY000): Can't connect to MySQL server on 'mysql:3307' (111)
python_app_1  | WARNING:werkzeug: * Debugger is active!
python_app_1  | INFO:werkzeug: * Debugger PIN: 111-520-781

我的Docker-Compose文件:

version: '3'

services:
  mysql:
    image: mysql:latest
    ports:
      - "3307:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: db
      MYSQL_USER: user
      MYSQL_PASSWORD: password
    networks:
      - sql_network
    volumes:
      - /mysql_data :/var/lib/mysql

  python_app:
    build: .
    ports:
      - "5000:5000"
    networks:
      - sql_network
    depends_on:
      - mysql

networks:
  sql_network:

DbService.py的相关部分:

config = {
    'host': 'mysql',  # This should match the service name in Docker Compose
    'port': '3307',   # This should match the exposed port on the host
    'user': 'user',
    'password': 'password',
    'database': 'db',
}


def create_tables():
    logger.info("Entering create tables method from dbservice")
    try:
        connection = mysql.connector.connect(**config)
        cursor = connection.cursor()
        # Check if 'emails' table already exists
        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()
    except Exception as e:
        logger.error(f"Unable to create tables due to {e}")

我的docker文件:

FROM python:3.12.1-bullseye

ARG REPO_DIR="."
ARG PROJECT_USER="randy"
ARG HOME_DIR="/home/$PROJECT_USER"
ARG DESTINATION_FOLDER="hdb"

WORKDIR $HOME_DIR

# The copy is from local (where the docker command is executed) to this 
COPY $REPO_DIR $DESTINATION_FOLDER

RUN pip install -r $DESTINATION_FOLDER/app/run-requirements.txt

RUN groupadd -g 2222 $PROJECT_USER && useradd -u 2222 -g 2222 -m $PROJECT_USER
RUN chown -R 2222:2222 $HOME_DIR && \
    rm /bin/sh && ln -s /bin/bash /bin/sh
USER 2222

WORKDIR $HOME_DIR/${DESTINATION_FOLDER}

CMD [ "python3", "app/app.py" ]

我的app.py的相关部分:

time.sleep(10)
create_tables()

本质上,我try 首先使用dbservice.py中的CREATE TABLES函数创建表,我将等待包括在内,因为我读到如果我在MySQL容器打开之前连接,可能会出现一些问题.

我可以使用docker exec -it <container image> bash连接到SQL容器并登录,没有问题,我看到容器已经启动并在docker-compose PS中运行.我只是在运行docker-compose build --no-cache && docker-compose up的时候无法连接到MySQL容器.这个问题困扰了我好几天,我已经在网上搜索了所有可能的解决方案,包括聊天,但都没有结果.我想这可能是我遗漏了一些小问题.有谁能帮忙吗?

推荐答案

您需要使用3306访问MySQL,因为它是MySQL在Docker容器内部监听的端口.

如果您try 使用在Docker外部运行的python脚本访问MySQL数据库,则需要使用端口3307,因为数据库是通过本地机器上的该端口连接的.

3307:3306是指您的数据库通过3307端口连接到您的本地机器,您的MySQL数据库通过3306端口连接到您的Docker容器网络内部.

Python相关问答推荐

仅对matplotlib的条标签中的一个条标签应用不同的格式

symy.分段使用numpy数组

在使用Guouti包的Python中运行MPP模型时内存不足

优化在numpy数组中非零值周围创建缓冲区的函数的性能

替换字符串中的多个重叠子字符串

SQLGory-file包FilField不允许提供自定义文件名,自动将文件保存为未命名

如何使用matplotlib在Python中使用规范化数据和原始t测试值创建组合热图?

Pandas 都是(),但有一个门槛

加速Python循环

用NumPy优化a[i] = a[i-1]*b[i] + c[i]的迭代计算

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

如果条件不满足,我如何获得掩码的第一个索引并获得None?

不允许访问非IPM文件夹

如何在turtle中不使用write()来绘制填充字母(例如OEG)

无法连接到Keycloat服务器

numpy.unique如何消除重复列?

Gekko中基于时间的间隔约束

并行编程:同步进程

不允许 Select 北极滚动?

递归函数修饰器