[英]Django on docker container error when trying to connect to local mysql database
Please help me,请帮我,
I have django application that run on docker container with docker-compose, but i have error when trying to connect to mysql database on my local machine.我有使用 docker-compose 在 docker 容器上运行的 django 应用程序,但是在尝试连接到本地机器上的 mysql 数据库时出现错误。
The error message is like this : Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'错误信息是这样的: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'
my docker-compose.yml file is like this :我的 docker-compose.yml 文件是这样的:
version: '3'
services:
web:
container_name: web
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
and my Dockerfile is like this :我的 Dockerfile 是这样的:
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY . /code/
RUN apt-get update
RUN apt-get install python3-dev default-libmysqlclient-dev -y
RUN pip install pip -U
RUN pip install -r requirements.txt
I have found how Django container have to access to the MySQL database that runs on the host,我发现了 Django 容器如何访问在主机上运行的 MySQL 数据库,
Private mode
.Private mode
。 Create a new Mysql user like this :像这样创建一个新的 Mysql 用户:
mysql > CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
mysql > GRANT ALL PRIVILEGES ON . TO 'monty'@'localhost'WITH GRANT OPTION;
mysql > CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
mysql > GRANT ALL PRIVILEGES ON . TO 'monty'@'%' WITH GRANT OPTION;
replace 'monty'
with username as you want to.根据需要将
'monty'
替换为用户名。
replace 'localhost'
with your host IP Address eg.将
'localhost'
替换为您的主机 IP 地址,例如。 192.168.1.50
replace 'some_pass'
with a password as you want.根据需要将
'some_pass'
替换为密码。
On Django settings.py file set Database setting like this :在 Django settings.py 文件中设置数据库设置如下:
DATABASES = {数据库 = {
'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'monitoring', # your database name 'USER': 'user1', # username that you just create above 'PASSWORD': 'root', # user password that you just create above 'HOST': '192.168.1.50', #your host IP Address where your mysql database run 'PORT': '3306', }}
Replace the bind-address = "127.0.0.1"
on my.cnf file to bind-address = "0.0.0.0"
将 my.cnf 文件中的
bind-address = "127.0.0.1"
替换为bind-address = "0.0.0.0"
This method is works for me and I hope this can work to all.这种方法对我有用,我希望这对所有人有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.