Reputation: 1431
I have set up Rstudio as a container on a server using a Rocker image. My MySQL instance is not in a docker and is running on the host machine. The db is a production database - so to dockerise the db as well isn't an option.
Can I connect to the host MySQL from inside the docker container running RStudio? 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.
Currently trying with R
just hanging in the end:
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:
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:
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'
Upvotes: 2
Views: 907
Reputation: 1781
Yes. You can run your image as host
mode.
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
.
When you run your container as host
mode, you can visit your Host's server. Here is MySQL with 127.0.0.1
instead of 172.17.0.1
.
Upvotes: 1