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
?
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
Instead of app-db
part I just want to connect to my locally hosted mysql
database.
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
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 111] Connection refused)")
I struggle solve above problem, While try to connect localhost mysql server from Dockerised flask app. Solution in this thread very usefull
Just use 172.17.0.1 inside docker. Its static ip address of host machine