When I tried to create a Django development environment with Docker, the only thing that didn't work was logging in to MySQL from Django.
This is what I have been suffering from for about 3 days. ..
django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'mysql' (11001)")
After trying to isolate the problem, the IP name resolution of the mysql container seems to work, and the ports and expose parts are not particularly mistaken, so the problem is the behavior after entering the MySQL container.
I couldn't find any good information on the Japanese site, but I searched for various English documents and finally solved it, so I summarized it.
proj/
├ docker/
│ ├ nginx/
│ │ └ default.conf
│ └ python/
│ ├ Dockerfile
│ └ requirements.txt
├ django_proj (The following is omitted)
├ docker-compose.yml
└ manage.py
Pay attention to the mysql settings in docker-compose.yml! (That's it! Lol)
docker-compose.yml
version: "3.9"
services:
python:
build: ./docker/python
command: gunicorn composeexample.wsgi:application --bind 0.0.0.0:8000 --reload
volumes:
- .:/code
expose:
- "8000"
nginx:
image: nginx:1.19
volumes:
- ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf
- ./static:/etc/nginx/static
ports:
- "80:80"
depends_on:
- python
mysql:
image: mysql:5.6
command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
volumes:
- ./docker/db/data:/var/lib/mysql
expose:
- "3306"
environment:
- MYSQL_ROOT_USER=root
- MYSQL_ROOT_PASSWORD=root
- MYSQL_ROOT_HOST=% #This one line was the point of this time
phpmyadmin:
image: phpmyadmin
ports:
- "8080:80"
environment:
- PMA_ARBITRARY=1
There was the following description on the MySQL official page.
MYSQL_ROOT_HOST: By default, MySQL creates the 'root'@'localhost' account. This account can only be connected to from inside the container as described in Connecting to MySQL Server from within the Container. To allow root connections from other hosts, set this environment variable. For example, the value 172.17.0.1, which is the default Docker gateway IP, allows connections from the host machine that runs the container. The option accepts only one entry, but wildcards are allowed (for example, MYSQL_ROOT_HOST=172...* or MYSQL_ROOT_HOST=%).
By default, the account is created with root @ localhost, so it seems that you can only log in as the root user from localhost, that is, the docker container.
So, if you add the description of MYSQL_ROOT_HOST =%
, you will be able to log in as the root user from any IP address, so I think that you can also log in from a different container. (maybe)
https://dev.mysql.com/doc/mysql-installation-excerpt/8.0/en/docker-mysql-more-topics.html#docker_var_mysql-root-host
Recommended Posts