如何将本地托管的MySQL数据库与Docker容器连接 [英] How to connect locally hosted MySQL database with the docker container

查看:440
本文介绍了如何将本地托管的MySQL数据库与Docker容器连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过docker-compose.yml我可以运行该应用程序.现在我们想将应用程序移至生产环境,但是我们不想使用容器数据库.有什么办法可以使我使用docker-compose将本地MySQL数据库与应用程序连接起来?

Through docker-compose.yml I am able to run the application. Now we want to move the application to production, But we don't want to use the container database. So is there any way so that I can connect my local MySQL database with the application using docker-compose?

我的docker-compose.yml看起来像:

My docker-compose.yml looks like:

version: '3'
services:
  web-app:
    build:
      context: .
      dockerfile: web-app/Dockerfile
    ports:
      - 8080:8080
    links:
      - app-db

  app-db:
    build:
      context: .
      dockerfile: app-db/Dockerfile

    environment:
    - MYSQL_ROOT_PASSWORD=password
    - MYSQL_DATABASE=Optimize
    ports:
      - 3306:3306

我只想连接到本地托管的mysql数据库,而不是app-db部分.

Instead of app-db part I just want to connect to my locally hosted mysql database.

推荐答案

在docker网络中查找主机ip.如果您使用docker-compose.yml version: "3",则可能是该IP地址:172.18.0.1但请确认,以搜索容器(您的主机)的网关":

Find the host machine ip in the docker network. If you use docker-compose.yml version: "3" it's probably that that IP is: 172.18.0.1, but confirm it searching for the "Gateway" of your container (your host):

docker inspect <container-id-or-name> | grep Gateway
"Gateway": "",
            "IPv6Gateway": "",
            "Gateway": "172.18.0.1",
            "IPv6Gateway": "",

因此,在您的docker应用程序内部,MySQL的指向如下:172.18.0.1:3306(也许在配置文件中).请注意,只要docker网络仍然相同,该IP就是固定的(该网络是由docker-compose创建的,除非您执行docker-compose down,否则它不会被删除)

So inside your docker application point to MySQL as this: 172.18.0.1:3306 (maybe in a configuration file). Take into account that that IP is fixed as long as the docker network still the same (the network is created by docker-compose, and it is not removed unless you do docker-compose down)

此外,检查您的MySQL是否正在侦听其所有接口.在my.cnf中搜索应为0.0.0.0bind-address(如果服务器具有公用IP,请考虑安全问题).

Also, check that your MySQL is listening to all of its interfaces. In your my.cnf search for bind-address that should be 0.0.0.0 (consider security issues if your server has public IP).

作为替代方案,您可以将与主机相同的网络带到容器中,以便共享本地主机,因此容器将在其中找到mysql.将网络模式用作主机":

As an alternative you can bring to the container the same networking as your host, in order to share the localhost, so the container will find mysql there. Use network mode as "host":

version: '3'
services:
  web-app:
    build:
      context: .
      dockerfile: web-app/Dockerfile
    ports:
       - 8080:8080
    network_mode: "host"

然后,将您的hibernate.properties指向mysql,如下所示:localhost:3306

Then, point in your hibernate.properties to mysql as this: localhost:3306

这篇关于如何将本地托管的MySQL数据库与Docker容器连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆