Search code examples
mysqldjangodockerdocker-composeconnection-refused

Docker with mysql and django. Connection to mysql is refused despite any attempts


So far I have tried everything I could find on the internet - but nothing seems to help.

This is my docker-compose.yml file:

version: '3.3'

services:
  ivs_fraud:
    build:
      context: .
      args:
        GIT_SSH_KEY: ${GIT_SSH_KEY}
    image: ivs_fraud:latest
    container_name: fraud
    depends_on:
      - ivsdb
    links:
      - ivsdb
    networks:
      - database_network

networks:
  database_network:
    driver: bridge

And I have a link / dependency to ivsdb service which is defined in another docker-compose-dev.yml file:

version: '3.3'

services:
  ivsdb:
    image: mysql
    container_name: ivsdb
    networks:
      - database_network
    ports:
      - ${DEFAULT_DB_PORT}:3306
    restart: always
    environment:
      MYSQL_DATABASE: ${DEFAULT_DB_NAME}
      MYSQL_USER: ${DEFAULT_DB_USER}
      MYSQL_PASSWORD: ${DEFAULT_DB_PASS}
      MYSQL_ROOT_PASSWORD: ${DEFAULT_DB_ROOT_PASS}

This is my .env file (Django reads this .env file and creates a connection according to it):

DEFAULT_DB_NAME=ivsdb
DEFAULT_DB_HOST=ivsdb
DEFAULT_DB_PORT=10001
DEFAULT_DB_USER=root
DEFAULT_DB_PASS=root
DEFAULT_DB_ROOT_PASS=root

And i keep getting:

(2003, 'Can\'t connect to MySQL server on \'ivsdb\' (111 "Connection refused")')

There are several modifications that i have tried with no success:

  1. Move everything into one docker-compose file
  2. Get rid of "networks" entry completely
  3. Change hosts to ivsdb / 127.0.0.1 / localhost / 0.0.0.0

Things that work:

  1. Djago service runs well
  2. Mysql service runs well.

I can connect to it using command line:

mysql -uroot -proot -P10001 --protocol=tcp 

or

mysql -uroot -proot -P10001 -h127.0.0.1 (IP adress enforces tcp protocol)

Looks like Django is having some hard time connecting to mysql container. But judging by "Connection refused" - django can reach mysql container.

What am I missing?


Solution

  • DEFAULT_DB_PORT=10001 should actually be MySQL's default port (3306), not the host-mapped port (10001)

    The difference is nicely explained here