Dockerized Django can't connect to MySQL

Naj*_*aji 0 python mysql django docker docker-machine

Using this tutorial https://semaphoreci.com/community/tutorials/dockerizing-a-python-django-web-application, I'm dockering my Django application in a VirtualBox using docker-machine. Everything has gone splendidly until I go to my browser and my application says that it's having issues with MySQL.

Then i found this documentation for dockerizing an instance of mysql https://github.com/mysql/mysql-docker which I followed, creating the image in the same development VirtualBox that I created. The error I was originally getting was

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'
Run Code Online (Sandbox Code Playgroud)

My Django DATABASES looked like this

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_name',
        'USER': 'root',
        'HOST': 'localhost',
        'PORT': ''
    }
}
Run Code Online (Sandbox Code Playgroud)

I then changed the host to 127.0.0.1 and even tried specifying the port as 3306 and I got a new error which was

(2003, "Can't connect to MySQL server on '127.0.0.1' (111)")
Run Code Online (Sandbox Code Playgroud)

I also went in to MySQL workbench and changed the connection of my Local instance to be 127.0.0.1:3306 and that hasn't helped.

The commands that I'm running are

eval "$(docker-image env development)" ---> supposedly does THESE things:

         export DOCKER_TLS_VERIFY="1"
         export DOCKER_HOST="tcp://123.456.78.910:1112"
         export DOCKER_CERT_PATH="/Users/me/.docker/machine/machines/development"
         export DOCKER_MACHINE_NAME="development"
Run Code Online (Sandbox Code Playgroud)

Then, now that i'm in my virtualbox, I run:

docker run -it -p 8000:8000 <docker image name> ---> forwards exposed port 8000 to port 8000 on my local machine

docker run -it -p 3306:3306 mysql/mysql-sever ---> forwards exposed port 3306 to port 3306 on my local machine

yam*_*enk 5

问题是您正在尝试连接127.0.0.1localhost从 django 容器的角度来看哪个将引用自身而不是 mysql 容器。

一般来说,对于容器进行通信,最好的“docker 方式”是让容器共享一个公共的 docker 网络。

docker network create mynet
docker run -it --network mynet -p 8000:8000 <docker image name>
docker run -it --network mynet -p 3306:3306 --name mysql mysql/mysql-sever
Run Code Online (Sandbox Code Playgroud)

现在应用程序容器可以使用mysql主机名和3306端口连接到 mysql 。