简体   繁体   English

从 rstudio docker 内部连接到主机 mysql 数据库

[英]connect to host mysql database from inside rstudio docker

I have set up Rstudio as a container on a server using a Rocker image.我已经使用 Rocker 图像将 Rstudio 设置为服务器上的容器。 My MySQL instance is not in a docker and is running on the host machine.我的 MySQL 实例不在 docker 中,而是在主机上运行。 The db is a production database - so to dockerise the db as well isn't an option. db 是一个生产数据库 - 所以 dockerise db 也不是一个选项。

Can I connect to the host MySQL from inside the docker container running RStudio?我可以从运行 RStudio 的 docker 容器内部连接到主机 MySQL 吗? The RStudio container runs perfectly, its just when I try and connect to the 'outside' MySQL to write data to db that I get a problem. RStudio 容器运行完美,就在我尝试连接到“外部”MySQL 以将数据写入数据库时​​,我遇到了问题。

Currently trying with R just hanging in the end:目前正在尝试使用R最终挂起:

library(RMySQL)
library(DBI)
  db_user <- Sys.getenv("server_user")
  db_password <- Sys.getenv("server_pass")
  db_host <- '172.17.0.1' # docker ip
  db_dbname <- "test"

  mydb <-
    dbConnect(
      MySQL(),
      user = db_user,
      password = db_password,
      dbname = db_dbname,
      host = db_host, 
      port = 3306
    )
Error in .local(drv, ...) : 
  Failed to connect to database: Error: Can't connect to MySQL server on '172.17.0.1' (107)

UPDATE, hack solution:更新,破解解决方案:

Wanting to keep the container running with all the port mapping I ended up adding a rule to the iptables and connecting to the database as if I was connecting to it from another server:为了让容器运行所有端口映射,我最终向 iptables 添加了一条规则并连接到数据库,就像我从另一台服务器连接到它一样:

sudo iptables -I INPUT 5 -p tcp -s 172.17.0.2 --dport 3306 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT -m comment --comment "docker DB access"

I also created a special docker user in MySQL that can access database:我还在 MySQL 中创建了一个可以访问数据库的特殊 docker 用户:

CREATE USER 'docker'@'172.17.0.2' IDENTIFIED BY 'XXX';
GRANT SELECT, INSERT, CREATE ON *.* 'docker'@'172.17.0.2' IDENTIFIED BY 'XXX';

Although its a bit of a hack, I avoid all the problems that come with --net='host'虽然它有点黑客,但我避免了 --net='host' 带来的所有问题

Yes.是的。 You can run your image as host mode.您可以将图像作为host模式运行。

docker run --net="host" ...

If you use host mode, mean you can't listen the same port in your container, because that will cause port already bind error .如果你使用host模式,意味着你不能在你的容器中监听同一个端口,因为这会导致port already bind error

When you run your container as host mode, you can visit your Host's server.当您以host模式运行容器时,您可以访问主机的服务器。 Here is MySQL with 127.0.0.1 instead of 172.17.0.1 .这是 MySQL 的127.0.0.1而不是172.17.0.1

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

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