How to connect locally hosted MySQL database with the docker container
If anybody is using mac os then please use docker.for.mac.host.internal
instead of host.docker.internal
as the environment variable.
Just use host.docker.internal
instead of localhost
.
To make it work on Linux, you just need to start your Docker container passing the parameter --add-host host.docker.internal:host-gateway
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": "",
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
)
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).
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"
Then, point in your hibernate.properties
to mysql as this: localhost:3306
Allow permission using mysqld.cnf
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
bind-address = 0.0.0.0
save your file and restart mysql server
sudo systemctl restart mysql.service
login to Mysql
mysql -h localhost -u root -p
GRANT ALL ON *.* TO 'root'@'localhost' IDENTIFIED BY 'yourpassword' WITH GRANT OPTION;
GRANT ALL ON *.* TO 'root'@'%' IDENTIFIED BY 'yourpassword' WITH GRANT OPTION;
FLUSH PRIVILEGES;
EXIT;
Find your IP
ip addr show
And use it in your docker container 192.168.x.x