How to associate a locally hosted MySQL database with a Docker container

Through docker-compose.yml I can run the application. Now we want to move the application to production, but we do not want to use the container database. So is there a way by which I can link my local MySQL database to the application using docker-compose ?

My docker-compose.yml looks like this:

 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 

Instead of the app-db I just want to connect to my local mysql database.

+9
source share
3 answers

Find the IP address of the host machine in the docker network. If you are using docker-compose.yml version: "3" , this IP address is 172.18.0.1 : 172.18.0.1 , but confirm the search 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, specify MySQL as follows: 172.18.0.1:3306 { 172.18.0.1:3306 (possibly in the configuration file). Note that this IP address is fixed as long as the docker network is still the same (the network is created using docker-compose, and it is not deleted if you do not run docker-compose down )

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


Alternatively, you can bring the same network to the container as your host to split the local host so that the container finds mysql there. Use network mode as a "host":

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

Then specify the mysql value in hibernate.properties as follows: localhost:3306

+17
source

Just use 172.17.0.1 inside the docker. Its static host IP

-1
source

Allow use of mysqld.cnf

 sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf bind-address = 0.0.0.0 

save your file and restart the MySQL server

 sudo systemctl restart mysql.service 

log in 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 dock container 192.168.xx

-1
source

Source: https://habr.com/ru/post/1268844/


All Articles