running python and mysql with docker error - cannot connect

做~自己de王妃 提交于 2021-01-29 08:17:08

问题


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)

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

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


回答1:


To create a docker from your linux machine:

docker pull mysql:latest

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

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>

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';

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"

Within Python:

import os

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

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.



来源:https://stackoverflow.com/questions/65460405/running-python-and-mysql-with-docker-error-cannot-connect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!