简体   繁体   English

如何使用 localhost 通过网桥连接到 mysql docker 实例?

[英]How to connect to mysql docker instance using localhost over network bridge?

I am running MySQL via docker-compose and trying to connect to it from the host, not another container, via a JDBC connection string for an app running on the host and not in a container.我正在通过 docker-compose 运行 MySQL 并尝试通过 JDBC 连接字符串从主机而不是另一个容器连接到它,以用于在主机上而不是在容器中运行的应用程序。 The environment is locked down, I cannot create new docker networks or bind a container to 'host' network, bridge is the only option.环境被锁定,我无法创建新的 docker 网络或将容器绑定到“主机”网络,桥接是唯一的选择。 I can connect to the MySQL instance using the IP address of the container, but this is not much use - I need to use localhost or 127.0.0.1 .我可以使用容器的 IP 地址连接到 MySQL 实例,但这没什么用 - 我需要使用localhost127.0.0.1 Is this possible?这可能吗? If so, how?如果是这样,怎么做?

docker-compose.yml docker-compose.yml

version: '2.2'
services:
  db:
    container_name: mysql_db
    image: mysql:5.7
    restart: always
    environment:
      MYSQL_DATABASE: 'test-db'
      MYSQL_USER: 'test-user'
      MYSQL_PASSWORD: 'password'
      MYSQL_ROOT_PASSWORD: 'password'
    network_mode: bridge
    ports:
      - '3306:3306'
    expose:
      - '3306'
volumes:
  my-db:

I can connect using the container's IP, like so:我可以使用容器的 IP 进行连接,如下所示:

 jdbc:mysql://172.17.0.3:3306/test-db

But cannot connect using localhost , 127.0.0.1 or the container name mysql_db like so:但无法使用localhost127.0.0.1或容器名称mysql_db连接,如下所示:

jdbc:mysql://localhost:3306/test-db
jdbc:mysql://127.0.0.1:3306/test-db
jdbc:mysql://mysql_db:3306/test-db

Any ideas?有任何想法吗?

Since 127.0.0.1 and localhost means the host your docker is currently running, so you cannot connect to your host's mysql .由于127.0.0.1localhost表示您的docker当前正在运行的host ,因此您无法连接到主机的mysql

I also recommend connect container using hostname :我还建议使用hostname连接容器:

docker run -it --network bridge --rm mysql mysql -hmysql_db -utest-user –ppassword

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

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