I am trying to connect mysql with docker using python. but this error is occurring. I am using python3. I am new in docker so I am unable to find any solution.
Dockerfile:
FROM python:3.8-alpine MAINTAINER Fahim Ahmed Irfan ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache jpeg-dev RUN apk --update add --no-cache --virtual .tmp-build-deps \ gcc build-base libffi-dev freetype-dev libpng-dev openblas-dev linux-headers mysql-dev zlib zlib-dev RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR ./app COPY ./app /app RUN adduser -D user User user EXPOSE 8000 Docker-compose file:
version: '3' services: app: restart: always build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python check_db.py --service-name mysql --ip db --port 3306 && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=app - DB_USER=root - DB_PASS=supersecretpassword depends_on: - db db: image: mysql:8.0 environment: - MYSQL_HOST=localhost - MYSQL_PORT=3306 - MYSQL_ROOT_HOST=% - MYSQL_DATABASE=app - MYSQL_USER=root - MYSQL_PASSWORD=supersecretpassword ports: - "3306:3306" check_db.py:
import socket import time import argparse """ Check if port is open, avoid docker-compose race condition """ parser = argparse.ArgumentParser(description='Check if port is open, avoid\ docker-compose race condition') parser.add_argument('--service-name', required=True) parser.add_argument('--ip', required=True) parser.add_argument('--port', required=True) args = parser.parse_args() # Get arguments service_name = str(args.service_name) port = int(args.port) ip = str(args.ip) # Infinite loop while True: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((ip, port)) if result == 0: print("{0} port is open! Bye!".format(service_name)) break else: print("{0} port is not open! I'll check it soon!".format(service_name)) time.sleep(3) settings.py:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), 'PORT': '3306', } requirements.txt:
Django==2.1.3,<2.2.0 djangorestframework==3.9.0,<3.10.0 pymysql The error is: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'db' ([Errno -2] Name does not resolve)")
Dont know how to solve this. Please advice.