gpt4 book ai didi

python - 无法连接到托管在 GCP Kubernetes Engine 上的 MySQL Docker

转载 作者:行者123 更新时间:2023-11-29 07:22:29 25 4
gpt4 key购买 nike

我想通过 Python 连接到托管在 GCP Kubernetes 上的 MySQL docker 来编辑数据库。我遇到错误:

2003, "Can't connect to MySQL server on '35.200.250.69' ([Errno 61] Connection refused)"

我也试过通过 MySQL 连接,也没有用

Docker环境

我的 Dockerfile:

FROM mysql:latest
ENV MYSQL_ROOT_PASSWORD password


# Derived from official mysql image (our base image)
FROM mysql
# Add a database
ENV MYSQL_DATABASE test-db
ENV MYSQL_USER=dbuser
ENV MYSQL_PASSWORD=dbpassword

# Add the content of the sql-scripts/ directory to your image
# All scripts in docker-entrypoint-initdb.d/ are automatically
# executed during container startup
COPY ./sql-scripts/ /docker-entrypoint-initdb.d/
EXPOSE 50050
CMD echo "This is a test." | wc -
CMD ["mysqld"]

sql-scripts 文件夹内容 2 个文件:

CREATE USER 'newuser'@'%' IDENTIFIED BY 'newpassword';
GRANT ALL PRIVILEGES ON * to 'newuser'@'%';

CREATE DATABASE test_db;

设置 GCP

我使用以下命令启动容器:

kubectl run test-mysql --image=gcr.io/data-sandbox-196216/test-mysql:latest --port=50050 --env="MYSQL_ROOT_PASSWORD=root_password"

在 GCP 上,容器似乎运行正常:

NAME         TYPE           CLUSTER-IP     EXTERNAL-IP     PORT(S)           AGE
test-mysql LoadBalancer 10.19.249.10 35.200.250.69 50050:30626/TCP 2m

连接Python

和连接到 MySQL 的 python 文件:

import sqlalchemy as db

# specify database configurations
config = {
'host': '35.200.250.69',
'port': 50050,
'user': 'root',
'password': 'root_password',
'database': 'test_db'
}
db_user = config.get('user')
db_pwd = config.get('password')
db_host = config.get('host')
db_port = config.get('port')
db_name = config.get('database')
# specify connection string
connection_str = f'mysql+pymysql://{db_user}:{db_pwd}@{db_host}:{db_port}/{db_name}'
# connect to database
engine = db.create_engine(connection_str)
connection = engine.connect()

我想做什么

我希望能够用 Python 编写这个 MySQL 数据库,并在 PowerBI 上读取它。

感谢您的帮助!

最佳答案

您已经暴露了端口50050,而MySQL 服务器默认监听端口3306

选项 I.my.cfg 中更改默认端口并设置 port=50050

选项 II. 公开默认的 MySQL 端口

docker 文件:

FROM mysql:latest
ENV MYSQL_ROOT_PASSWORD password


# Derived from official mysql image (our base image)
FROM mysql
# Add a database
ENV MYSQL_DATABASE test-db
ENV MYSQL_USER=dbuser
ENV MYSQL_PASSWORD=dbpassword

# Add the content of the sql-scripts/ directory to your image
# All scripts in docker-entrypoint-initdb.d/ are automatically
# executed during container startup
COPY ./sql-scripts/ /docker-entrypoint-initdb.d/
EXPOSE 3306
CMD echo "This is a test." | wc -
CMD ["mysqld"]

启动容器:

kubectl run test-mysql --image=gcr.io/data-sandbox-196216/test-mysql:latest --port=3306 --env="MYSQL_ROOT_PASSWORD=root_password"

关于python - 无法连接到托管在 GCP Kubernetes Engine 上的 MySQL Docker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55509333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com