我的主机中的 Flask 应用程序连接到虚拟机中 Docker 中的 MySQL

问题描述 投票:0回答:1

所以本质上,我有一个简单的 Flask 应用程序在我的主机上运行,我试图连接到一个具有 MySQL 并安装在我的 VM(虚拟盒)中的 docker 容器。我无法这样做,因为

ERROR:__main__:Error connecting to MySQL database: 2003 (HY000): Can't connect to MySQL server on 'dockerip:3306' (60)

上面的“dockerip”我在这里手动更改了它,但它是我运行时得到的值

sudo docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' mysqlcontainerflask

因此,一些基本信息,在我的虚拟机的网络配置中,我设置了端口转发以从我的主机获取连接:

并且,从我的主机,我可以使用以下命令连接到虚拟机中的 docker:

mysql -h 127.0.0.1 -P 7703 -u root -p

这告诉我,我的虚拟机中包含 MySQL 的 docker 正在接受来自我的主机的连接?

无论如何,我的 Flask 应用程序的代码如下:

from flask import Flask, render_template, request
import paramiko
import mysql.connector
import logging

app = Flask(__name__)

# Configure logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/search', methods=['POST'])
def search():
    search_query = request.form.get('search_query')

    # MySQL database configuration
    db_config = {
        'host': 'dockerip (this has the ip as I mentioned above)', 
        'port': 3306,           # MySQL port
        'user': 'root',         # MySQL username
        'password': 'thishasthepassword',  # MySQL password
        'database': 'cache_db'  # MySQL database name
    }

    try:
        # Connect to MySQL database
        db_connection = mysql.connector.connect(**db_config)
        db_cursor = db_connection.cursor()

        # Check if search query exists in the database
        db_cursor.execute("SELECT result FROM cache WHERE query = %s", (search_query,))
        cached_result = db_cursor.fetchone()

        if cached_result:
            # If cached result exists, return it
            response = cached_result[0]
        else:
            # If no cached result, perform search on Wikipedia
            response = perform_wikipedia_search(search_query)

            # Cache the search result in the database
            db_cursor.execute("INSERT INTO cache (query, result) VALUES (%s, %s)", (search_query, response))
            db_connection.commit()

        db_cursor.close()
        db_connection.close()

        return render_template('search.html', search_query=search_query, response=response)

    except mysql.connector.Error as e:
        logger.error("Error connecting to MySQL database: %s", e)
        return render_template('error.html', error_message="Failed to connect to the database")

def perform_wikipedia_search(search_query):
    try:
        instance_ip = "myinstanceipgoeshere"
        securityKeyFile = "mypemfilegoeshere"  

        logger.info("Attempting SSH connection...")
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        key = paramiko.RSAKey.from_private_key_file(securityKeyFile)
        client.connect(hostname=instance_ip, username="ubuntu", pkey=key)
        logger.info("SSH connection successful!")

        cmd = f"python3 /home/wiki.py '{search_query}'"
        stdin, stdout, stderr = client.exec_command(cmd)
        stdin.close()
        output = stdout.read().decode('utf-8')  # Get the output and decode it
        client.close()

        logger.info("Output from Wikipedia search:")
        logger.info(output)  # Log the output for debugging

        return output

    except Exception as e:
        logger.error("Error performing Wikipedia search: %s", e)
        return str(e)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001)

所以基本上这是一个应用程序,应该接受搜索查询,将搜索存储在数据库中并将其用作将来搜索的缓存。然而,当我运行 Flask 应用程序并尝试搜索时,我会得到:

内部服务器错误 服务器遇到内部错误,无法完成您的请求。服务器超载或应用程序出现错误。

和 PyCharm 日志:

ERROR:__main__:Error connecting to MySQL database: 2003 (HY000): Can't connect to MySQL server on 'dockerip:3306' (60)

再次,我替换了“dockerip”的实际 IP,只是将其放在这里。

我认为我的观点是我不确定我在这里错过了什么。我认为我可以从我的主机连接到 MySQL docker 的事实表明从我的主机到我的虚拟机中的 Docker 的连接很好,所以接下来要检查的是凭据,所以我三次检查了数据库名称、主机 IP(这是我通过上面的方法获得的 dockerip)、用户名和密码,但没有运气:(

如果有人知道这里可能出了什么问题,请吗?

python mysql flask virtual-machine virtualbox
1个回答
0
投票

所以我应该使用我的本地主机(127.0.0.1)作为主机IP而不是容器的IP。这就解决了这个问题。我很困惑,因为我认为我应该使用MySQL的主机ip,在我的脑海中这是运行mysql的容器(容器是“托管”mysql),但我想我错了!

感谢看过的人,希望这对其他人有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.