fahim irfan
fahim irfan

Reputation: 78

Can't connect to MySQL server on 'db' ([Errno -2] Name does not resolve)

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.

Upvotes: 2

Views: 3083

Answers (1)

Mehant Kammakomati
Mehant Kammakomati

Reputation: 880

Finally I got this working, I have made a few important changes that are required for your code.

WORKDIR app

WORKDIR does the creation of the directory app and also moving into the directory app so you can remove the statement RUN mkdir /app As you also move to that directory so change the COPY statement to

COPY . .

first . is the place where the dockerfile exists and the second . is the app folder in the container. So it is always good to have dockerfile in the app folder.

    volumes:
      - ./app:/app

the above code from the docker-compose is not required as you are copying the contents directly so mounting again is of no use.

      - MYSQL_ROOT_PASSWORD=supersecretpassword

Also, add the above environment variable to the db service in the docker-compose

- MYSQL_HOST=localhost

Please remove this environment variable as it is not required here.

image: mysql:5.7

I would recommend using version 5.7 as it is one of the stable ones I extensively use without many issues from the database server.

Upvotes: 3

Related Questions