运行 python 和 mysql 时出现 docker 错误 - 无法连接 [英] running python and mysql with docker error - cannot connect

查看:95
本文介绍了运行 python 和 mysql 时出现 docker 错误 - 无法连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 mysql-connector,每当我使用 docker 运行容器时,我都会收到此错误:

I am using mysql-connector, when ever I run the container using docker I get this error:

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'db:3306' (-5 No address associated with hostname)

但是当我使用 python 运行项目时,它只执行没有错误

but when I run the project using python only it executes with no errors

我只想将 phpmyadmin 用于数据库,请帮忙.

I want to use phpmyadmin only for the database please help.

推荐答案

从你的 linux 机器创建一个 docker:

To create a docker from your linux machine:

docker pull mysql:latest

要运行它并在 3306(mysql 的标准端口)上挂载具有端口访问权限的持久文件夹:

To run it and mount a persistent folder with port access on 3306 (std port for mysql):

docker run --name=mysql_dockerdb --env="MYSQL_ROOT_PASSWORD=<your_password>" -p 3306:3306 -v /home/ubuntu/sql_db/<your_dbasename>:/var/lib/mysql -d mysql:latest

连接到 docker 实例以便您可以在 docker 中创建数据库:

To connect to the docker instance so that you can create the database within the docker:

docker exec -it mysql_dockerdb mysql -uroot -p<your_password>

我建立数据库的SQL代码:

My SQL code to establish the database:

CREATE DATABASE dockerdb;
CREATE USER 'newuser'@'%' IDENTIFIED BY 'newpassword';
GRANT ALL PRIVILEGES ON dockerdb.* to 'newuser'@'%';
ALTER USER 'username'@'%' IDENTIFIED WITH mysql_native_password BY 'userpassword';

您现在将拥有一个运行持久 SQL 数据库的 docker.您可以从 Python 代码连接到它.我正在运行 Flask mySql.您将希望将密码保存在环境变量中.我使用的是 Mac,因此我的 ~/.bash_profile 包含:

You will now have a docker running with a persistent SQL database. You connect to it from your Python code. I am running Flask mySql. You will want to keep your passwords in environment variables. I am using a Mac so therefore my ~/.bash_profile contains:

export RDS_LOGIN="mysql+pymysql://<username>:<userpassword>@<dockerhost_ip>/dockerdb"

在 Python 中:

Within Python:

import os

SQLALCHEMY_DATABASE_URI = os.environ.get('RDS_LOGIN')

到那时,您应该能够以通常的 Python 方式进行连接.请注意,我在假设这是本地防火墙后忽略了任何安全方面.

And at that point you should be able to connect in your usual Python manner. Note that I've glossed over any security aspects on the presumption this is local behind a firewall.

这篇关于运行 python 和 mysql 时出现 docker 错误 - 无法连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆