2017-08-13 149 views
1

我有一个使用Flask和MySQL的应用程序。应用程序不会连接到Flask应用程序的MySQL容器,但可以使用Sequel Pro以相同的凭据访问它。从Flask连接到MySQL使用docker-compose的应用程序

泊坞撰写文件

version: '2' 
services: 
    web: 
    build: flask-app 
    ports: 
    - "5000:5000" 
    volumes: 
    - .:/code 
    mysql: 
    build: mysql-server 
    environment: 
     MYSQL_DATABASE: test 
     MYSQL_ROOT_PASSWORD: root 
     MYSQL_ROOT_HOST: 0.0.0.0 
     MYSQL_USER: testing 
     MYSQL_PASSWORD: testing 
    ports: 
     - "3306:3306" 

泊坞文件为MySQL

MySQL的搬运工文件将从test.dump文件添加架构。

FROM mysql/mysql-server 
ADD test.sql /docker-entrypoint-initdb.d 

泊坞立案瓶

FROM python:latest 
COPY . /app 
WORKDIR /app 
RUN pip install -r requirements.txt 
ENTRYPOINT ["python"] 
CMD ["app.py"] 

起点app.py

from flask import Flask, request, jsonify, Response 
import json 
import mysql.connector 
from flask_cors import CORS, cross_origin 

app = Flask(__name__) 

def getMysqlConnection(): 
    return mysql.connector.connect(user='testing', host='0.0.0.0', port='3306', password='testing', database='test') 

@app.route("/") 
def hello(): 
    return "Flask inside Docker!!" 

@app.route('/api/getMonths', methods=['GET']) 
@cross_origin() # allow all origins all methods. 
def get_months(): 
    db = getMysqlConnection() 
    print(db) 
    try: 
     sqlstr = "SELECT * from retail_table" 
     print(sqlstr) 
     cur = db.cursor() 
     cur.execute(sqlstr) 
     output_json = cur.fetchall() 
    except Exception as e: 
     print("Error in SQL:\n", e) 
    finally: 
     db.close() 
    return jsonify(results=output_json) 

if __name__ == "__main__": 
    app.run(debug=True,host='0.0.0.0') 

当我使用REST客户端,我得到一个有效的响应做http://localhost:5000/ GET请求。

http://localhost:5000/api/getMonths GET请求给出错误信息:

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on '0.0.0.0:3306' (111 Connection refused) 

当同样的证书是在续集专业,我是能够访问数据库中。 enter image description here

请咨询我如何连接来自Flask应用程序的MySQL容器。这是我第一次起诉Docker,如果这是我的愚蠢错误,请原谅我。

回答

1

更改此

return mysql.connector.connect(user='testing', host='0.0.0.0', port='3306', password='testing', database='test') 

return mysql.connector.connect(user='testing', host='mysql', port='3306', password='testing', database='test') 

你的代码是在容器内,而不是你的主机上运行。所以你需要为它提供一个可以在集装箱网络内到达的地址。对于docker-compose,每个服务都可以使用其名称进行访问。所以在你的这是mysql,因为这是你用于服务的名称

相关问题