我已经在运行一个名为“ mysqlDemoStorage”的mysql容器,将端口3306暴露给0.0.0.0:3306。我也有一个flask应用程序,它提供了登录页面和表显示页面。 flask应用程序在主机上运行良好。登录页面连接到mysql容器中的“用户”表,而表显示页面连接到包含所有要显示数据的表。 我用来创建mysql容器的docker-compose文件如下:
version: '3'
services:
mysql:
container_name: mysqlDemoStorage
environment:
MYSQL_ROOT_PASSWORD: "demo"
command:
--character-set-server=utf8
ports:
- 3306:3306
image: "docker.io/mysql:latest"
restart: always
现在,我想对烧瓶应用程序进行docker化,以便仍可以从主机查看该应用程序。 mysql容器的详细信息如下:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c48955b3589e mysql:latest "docker-entrypoint.s…" 13 days ago Up 49 minutes 0.0.0.0:3306->3306/tcp, 33060/tcp mysqlDemoStorage
我编写的flask应用程序的dockerfile如下:
FROM python:latest
WORKDIR /storage_flask
ADD . /storage_flask
RUN pip install -r requirements.txt
EXPOSE 5000
ENTRYPOINT ["python","run.py"]
烧瓶图像可以成功构建,但是运行图像时,我无法加载页面。我认为引起问题的一点是 init .py文件来启动flask应用程序,如下所示:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = 'aafa4f8047ce31126011638be8530da6'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:demo@localhost:3306/storage'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = "login"
login_manager.login_message_category = 'info'
from storage_flask import routes
我正在考虑将mysql容器的IP作为数据库连接的配置字符串传递到flask容器。但是我不确定该怎么做。 有人可以帮助解决问题吗?谢谢
答案 0 :(得分:0)
更改此行
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:demo@localhost:3306/storage'
到
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:demo@mysql:3306/storage'
您还需要确保两个容器都连接到同一网络,因为您需要将docker-compose文件更新为类似于以下文件
version: '3.7'
networks:
my_network_name:
name: my_network_name
external: false
services:
mysql:
container_name: mysqlDemoStorage
environment:
MYSQL_ROOT_PASSWORD: "demo"
command:
--character-set-server=utf8
ports:
- 3306:3306
image: "docker.io/mysql:latest"
restart: always
networks:
- my_network_name
第二个文件
version: '3.7'
networks:
my_network_name:
name: my_network_name
external: true
services:
python_app:
container_name: pythonDemoStorage
ports:
- 5000:5000
image: "Myimage"
restart: always
networks:
- my_network_name