首页 > 解决方案 > docker 上的烧瓶应用程序中的 mysql-connector-python 未连接

问题描述

我的本地主机没有问题,在我的电脑上运行良好,但在 docker 中没有运行,这个错误

连接的

def get_database_connection():
    """connects to the MySQL database and returns the connection"""
    return mysql.connector.connect(
        host=config.MYSQL_HOST,
        user=config.MYSQL_USERNAME,
        passwd=config.MYSQL_PASSWORD,
        db = config.MYSQL_DB_NAME,
        port=config.MYSQL_PORT,
        charset='utf8'
    )

配置文件

MYSQL_HOST = "localhost"
MYSQL_USERNAME = "root" 
MYSQL_PASSWORD = ""
MYSQL_PORT = 3306
MYSQL_DB_NAME = "newsdb"

- - - - - 错误 - - - -

** Operational MODE: preforking ***
build Tables
error --- > 2003 (HY000): Can't connect to MySQL server on 'localhost' (99)
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x55e5696d31a0 pid: 10 (default app)
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** 

项目结构


app
├── admin
│   ├── api.py
│   ├── config.py
│   ├── db.py
│   ├── __init__.py
│   ├── routes.py
│   ├── static
│   └── templates
├── config.py
├── db.py
├── error_handlers.py
├── __init__.py
├── robots
│   ├── robot_runner.py
│   └── robots.py
├── routes.py
├── schema.sql
├── static
│   
├── templates
└── test

Dockerfile

FROM tiangolo/uwsgi-nginx-flask:python3.8


COPY . /app

RUN python -m pip install --upgrade pip

COPY ./requirements.txt /var/www/requirements.txt

RUN apt update && apt install -qy libmariadbclient-dev gcc

RUN pip3 install -r /var/www/requirements.txt


这个项目在我的本地主机上运行,​​没有问题......只想运行 image docker show error 而不是连接到 mysql ..

标签: pythondockerdockerfileflask-restful

解决方案


Dockerfile不包括带有图像的 MySQL 服务器。容器的最佳实践是在每个容器中保留一项服务,因此运行容器化的 MySQL 服务意味着运​​行两个单独的容器——一个用于您的 Web 应用程序,一个用于您的 MySQL 服务器。

docker-compose是处理这个用例的合理方式。指定一个docker-compose.yml包含您的服务定义:

version: '2.0'
services:
  web:
    build: .
    ports: [ "5000:5000" ]
    links: [ "mysql" ]
  mysql:
    image: mysql
    [... some other configuration parameters to set up the database root account ...]
    volumes: [ "mysqldata:/var/lib/mysql" ]
volumes: { mysqldata: {} }

这里引用的MySQL 镜像是 Docker Hub 上的官方 MySQL 镜像

在此之后,您可以在应用程序的配置文件中连接到“mysql”而不是“localhost”。

或者,将您的应用程序配置文件指向已设置数据库的已运行 MySQL 服务。请记住,localhost容器中的不是您的本地机器——它是容器。您可能需要为容器适当地配置 Docker 网络以访问您的机器或 MySQL 主机。


推荐阅读