从容器内连接到远程mysql数据库

时间:2018-06-14 19:43:11

标签: mysql docker docker-networking

从我的本地计算机,我可以使用mysql cli命令轻松连接到mysql数据库的远程实例(假设设置了环境变量):

# mysql -u root -p$DB_PASSWORD -h $DB_HOST --port=$DB_PORT

mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7365
Server version: 5.7.14-google (Google)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.05 sec)

但是,使用docker它只会挂起:

docker run --rm -it --name mysql -e MYSQL_RANDOM_ROOT_PASSWORD=yes mysql \
mysql -u root -p$DB_PASSWORD -h $DB_HOST --port=$DB_PORT

mysql: [Warning] Using a password on the command line interface can be insecure.
show databases;
^C
^C
exit
exit
^C

并且必须从另一个终端窗口docker container stop mysql才能退出mysql容器。

我甚至尝试连接到容器并运行相同的命令无济于事。尝试连接到AWS MySQL实例和Google Cloud SQL实例,也尝试直接在命令行中输入变量,但结果相同。它为什么悬挂,我怎样才能使它工作?谢谢!

3 个答案:

答案 0 :(得分:0)

尝试公开MySQL的默认端口

docker run -p 3306:3306 ...

答案 1 :(得分:0)

我使用的是Google Cloud SQL,并且需要将其列入白名单才能允许访问。所以添加解决了连接问题。

答案 2 :(得分:0)

我尝试了所有方法,但以下步骤解决了我的问题。 在容器内运行命令

dpkg-重新配置tzdata

它将要求您选择“地理区域”和“时区”,然后完成。