Skip to content Skip to sidebar Skip to footer

Running Python And Mysql With Docker Error - Cannot Connect

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

Solution 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;
CREATEUSER'newuser'@'%' IDENTIFIED BY'newpassword';
GRANTALL PRIVILEGES ON dockerdb.*to'newuser'@'%';
ALTERUSER'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:

importosSQLALCHEMY_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.

Post a Comment for "Running Python And Mysql With Docker Error - Cannot Connect"