简体   繁体   English

Python 无法使用 docker 连接到 mysql

[英]Python can't connect to mysql using docker

I'm new to docker and right now I'm trying to use mysql in my mac without install it so I wanted to use Docker but I keep getting this error我是 docker 的新手,现在我正在尝试在我的 Mac 中使用 mysql 而不安装它,所以我想使用 Docker 但我一直收到此错误

sqlalchemy.exc.InterfaceError: (mysql.connector.errors.InterfaceError) 2003: Can't connect to MySQL server on 'localhost:3306' (61 Connection refused) sqlalchemy.exc.InterfaceError: (mysql.connector.errors.InterfaceError) 2003: Can't connect to MySQL server on 'localhost:3306' (61 Connection denied)

Reproduce the problem:重现问题:

I pulled mysql/mysql-server:我拉了mysql/mysql-server:

docker pull mysql/mysql-server

Inside the terminal:航站楼内:

docker run --name=mydb -d mysql/mysql-server

Then I changed its password into:123456然后我把它的密码改成:123456

Inside the code database.py:在代码database.py里面:

SQLALCHEMY_DATABASE_URL = 'mysql+mysqlconnector://mydb:123456@localhost:3306/authorize_info'

At this step I will get this error在这一步我会得到这个错误

sqlalchemy.exc.InterfaceError: (mysql.connector.errors.InterfaceError) 2003: Can't connect to MySQL server on 'localhost:3306' (61 Connection refused) sqlalchemy.exc.InterfaceError: (mysql.connector.errors.InterfaceError) 2003: Can't connect to MySQL server on 'localhost:3306' (61 Connection denied)

I also got this error when I changed 'localhost' into '172.17.0.1'当我将“localhost”更改为“172.17.0.1”时,我也遇到了这个错误

Where am I wrong and how to fix it?我在哪里错了,如何解决? Please help me请帮我

When you run a container, it doesn't automatically map its ports to the ports on your machine.当您运行容器时,它不会自动将其端口 map 其端口连接到您机器上的端口。 You need to tell docker what the port in the container should be mapped to on your local machine by using the -p option.您需要使用-p选项告诉 docker 容器中的端口应该映射到本地计算机上的哪个端口。 If you want to be able to access port 3306 in the container by using port 3306 on your local machine, you should start the container like this如果您希望能够通过使用本地计算机上的端口 3306 访问容器中的端口 3306,您应该像这样启动容器

docker run --name=mydb -d -p 3306:3306 mysql/mysql-server

The first number is the port on your local machine and the second number is the port in the container.第一个数字是本地计算机上的端口,第二个数字是容器中的端口。

there is one more thing.还有一件事。 you can user name of a container to connect if if your app is in the same network as database.如果您的应用程序与数据库位于同一网络中,您可以使用容器的用户名进行连接。 if not, you should use host IP to connect to the database.如果没有,您应该使用主机 IP 连接到数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM