here is my docker-compose.yml file
services:
db:
image: mysql
ports:
- '3306:3306'
environment:
MYSQL_DATABASE: 'app'
MYSQL_USER: 'root'
MYSQL_PASSWORD: 'aspilos'
MYSQL_ROOT_PASSWORD: 'aspilos'
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/aspilos
ports:
- "8000:8000"
depends_on:
- db
Here is my utils.py file
import mysql.connector
mydb = mysql.connector.connect(
host="db",
user="root",
passwd="aspilos",
database="aspilos_log",
auth_plugin="mysql_native_password"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT CONCAT('+', PHONE_NUMBER) FROM category2")
results = mycursor.fetchall()
for i in zip(*results):
number = list(i)
number1 = '+2348076548894'
print (number)
Here is my settings.py file
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'app',
'USER': 'root',
'PASSWORD': 'aspilos',
'HOST': 'db',
'PORT': '3306',
},
}
"docker-compose up" everything works fine and it opens locally But when i run
"python manage.py runserver"it pops up an errormysql.connector.errors.DatabaseError: 2005 (HY000): Unknown MySQL server host 'db' (2)
Database Host DB will only work in the docker-compose network. You can connect to other service using service name inside docker-compose but it becomes invalid outside of the docker-network.
A common error that can occur in docker-compose is when Database is not yet ready but application try to connect, a quick and dirty fix for that can be
webapp:
build: .
image: webapp
command: sh -c "sleep 30s ; python /app/manage.py"
But you should implement retry logic.
To deal with the above error you need a DNS that host or system can resovle
mydb = mysql.connector.connect(
host="REACHABLE_IP",
....
)
You can verify reachable IP by connecting through the DB, it can
MySQL -h REACHABLE_IP -u db_user -pPass