sqlalchemy cannot connect to MYSQL server on '127.0.0.1'
Question:
I am trying to dockerize powerdns-admin and the app needs connection a database, the database i use is mariadb via sqlalchemy.
The docker-compose:
docker-compose.yml
version: "3"
services:
app:
image: ngoduykhanh/powerdns-admin:latest
container_name: powerdns_admin
ports:
- "9191:80"
logging:
driver: json-file
options:
max-size: 50m
environment:
- SQLALCHEMY_DATABASE_URI=mysql://root:[email protected]/powerdns
- GUNICORN_TIMEOUT=60
- GUNICORN_WORKERS=2
- GUNICORN_LOGLEVEL=DEBUG
- OFFLINE_MODE=False # True for offline, False for external resources
When i run docker-compose up -d
it only outputs the following error:
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (2002, "Can't connect to MySQL server on '127.0.0.1' (115)")
When i do mysql -uroot -pdbpass
from the host of the docker-compose, i can connect successfully.
same when i run the following commands from the mysql host:
mysql -uroot -pdbpass -h 127.0.0.1
mysql -uroot -pdbpass -h localhost
What is wrong?
Answers:
When you run a docker container, you it behaves a lot like a separate machine. When you try to connect to 127.0.0.1 you’re trying to connect to the container itself. Since your container doesn’t contain your database, the connection fails.
From inside a container you can reach the host machine on ip address 172.17.0.1. So your database URI should be
SQLALCHEMY_DATABASE_URI=mysql://root:[email protected]/powerdns
I am trying to dockerize powerdns-admin and the app needs connection a database, the database i use is mariadb via sqlalchemy.
The docker-compose:
docker-compose.yml
version: "3"
services:
app:
image: ngoduykhanh/powerdns-admin:latest
container_name: powerdns_admin
ports:
- "9191:80"
logging:
driver: json-file
options:
max-size: 50m
environment:
- SQLALCHEMY_DATABASE_URI=mysql://root:[email protected]/powerdns
- GUNICORN_TIMEOUT=60
- GUNICORN_WORKERS=2
- GUNICORN_LOGLEVEL=DEBUG
- OFFLINE_MODE=False # True for offline, False for external resources
When i run docker-compose up -d
it only outputs the following error:
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (2002, "Can't connect to MySQL server on '127.0.0.1' (115)")
When i do mysql -uroot -pdbpass
from the host of the docker-compose, i can connect successfully.
same when i run the following commands from the mysql host:
mysql -uroot -pdbpass -h 127.0.0.1
mysql -uroot -pdbpass -h localhost
What is wrong?
When you run a docker container, you it behaves a lot like a separate machine. When you try to connect to 127.0.0.1 you’re trying to connect to the container itself. Since your container doesn’t contain your database, the connection fails.
From inside a container you can reach the host machine on ip address 172.17.0.1. So your database URI should be
SQLALCHEMY_DATABASE_URI=mysql://root:[email protected]/powerdns