[英]Cannot connect to MySQL service in MySQL docker container?
So, I've got a MySQL docker container on which I run a script to write into the database, but when I execute the script, my script throws所以,我有一个 MySQL docker 容器,我在上面运行脚本写入数据库,但是当我执行脚本时,我的脚本抛出
mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)
Do I have to start the MySQL service in the Dockerfile?必须要在Dockerfile中启动MySQL服务吗?
docker-compose.yml: docker-compose.yml:
version: '3.3'
services:
db:
build: .
restart: always
environment:
MYSQL_ROOT_PASSWORD: test
MYSQL_DATABASE: test
MYSQL_USER: test
MYSQL_PASSWORD: test
volumes:
- ./db_data:/docker-entrypoint-initdb.d
First you need to expose the MySQL port 3306
or any other port you set for the MySQL and then you can get help from commmand
parameter.首先,您需要公开 MySQL 端口
3306
或您为commmand
设置的任何其他端口,然后您可以从命令参数获得帮助。
A working sample would be like this:一个工作样本是这样的:
version: '3.1'
services:
db:
image: mysql
container_name: mysql_test
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: root_password
MYSQL_DATABASE: test
MYSQL_USER: test_user
MYSQL_PASSWORD: test_password
ports:
- 30001:3306
expose:
- 30001
volumes:
- my-db:/var/lib/mysql
networks:
- test
networks:
test:
volumes:
my-db:
driver: local
With this sample code you will be able to connect with localhost:30001
to your database from host machine and mysql_test:3306
from other containers within the same.network.使用此示例代码,您将能够使用
localhost:30001
从主机连接到您的数据库,并从同一网络中的其他容器连接到mysql_test:3306
。
If you're trying to execute script in your host, you need to export port 3306如果你想在你的主机上执行脚本,你需要导出端口 3306
version: '3.3'
services:
db:
build: .
restart: always
environment:
MYSQL_ROOT_PASSWORD: test
MYSQL_DATABASE: test
MYSQL_USER: test
MYSQL_PASSWORD: test
ports:
- 3306:3306
volumes:
- ./db_data:/docker-entrypoint-initdb.d
If you're trying to execute inside docker (with a docker exec for example), check if container is up with docker ps
如果您尝试在 docker 内部执行(例如使用 docker exec),请检查容器是否已启动
docker ps
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.