简体   繁体   English

在Docker容器中使用MySQL

[英]Using MySQL in a Docker Container

I am kinda new to Docker and I am trying to build an image for a Django App using MySQL. 我是Docker的新手,我正在尝试使用MySQL为Django应用构建映像。 The problem that I am having is, after running my image I get the following error : django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)") . 我遇到的问题是,运行映像后,出现以下错误: django.db.utils.OperationalError:(2002,“无法通过套接字'/ var / run / mysqld / mysqld连接到本地MySQL服务器。袜子((111)“) As a base for the image I am using FROM django:python2 , I have installed the server using the following commands: 作为我使用FROM django:python2的映像的基础,我已经使用以下命令安装了服务器:

  • RUN echo "mysql-server mysql-server/root_password password X" | debconf-set-selections
  • RUN echo "mysql-server mysql-server/root_password_again password X" | debconf-set-selections
  • RUN apt-get update && apt-get install -y mysql-server

To fix the problem I tried multiple solutions, which I found on the internet such as: 为了解决该问题,我尝试了多种解决方案,这些解决方案是在互联网上找到的,例如:

  • RUN touch /var/run/mysqld/mysqld.sock
  • RUN chmod -R 755 /var/run/mysqld/mysqld.sock
  • EXPOSE 3306

Sadly, nothing worked. 可悲的是,没有任何效果。 I also made sure the server is running, yet the problem is still there. 我还确保服务器正在运行,但问题仍然存在。

Here is an example config that works really well. 这是一个效果很好的示例配置。

Dockerfile Dockerfile

FROM python:3.5
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD . /code/
RUN pip install -r requirements.txt

Make sure to change the path to your requirements.txt file (if exists.) 确保将路径更改为您的requirements.txt文件(如果存在)。

docker-compose.yml 泊坞窗,compose.yml

db:
  image: mysql
web:
  build: .
  environment:
    - PYTHONPATH=/code/server/
    - DJANGO_SETTINGS_MODULE=path.to.your.settings.file
  command: python server/manage.py runserver 0.0.0.0:8000
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  links:
    - db

Make sure to replace the path to DJANGO_SETTINGS_MODULE with the correct dotted-path to your settings file. 确保将DJANGO_SETTINGS_MODULE的路径替换为设置文件的正确虚线路径。

docker-compose build then docker-compose up docker-compose build然后docker-compose up

EDIT 编辑

If you use this config, change the value of HOST to db in your settings.py 如果使用此配置,请在settings.py中将HOST的值更改为db

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM