使用 docker-compose 链接 django 和 mysql 容器

我一直在关注 docker-compose 教程这里(链接 django 和 postgres容器).虽然我能够完成教程,但我无法继续重复相同的内容使用 mysql 容器.以下是我的 dockerfile 和 docker-compose.yml`

I've been following with the docker-compose tutorial here (linking django and postgres container). Although I was able to go through with the tutorial I'm however not able to proceed with repeating the same using a mysql container. The following are my dockerfile and docker-compose.yml `

db:
  image: mysql
web:
  build: .
  command: python manage.py runserver 0.0.0.0:8000
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  links:
    - db:db

`docker文件

FROM python:2.7
RUN mkdir /code
WORKDIR /code
RUN pip install mysql-python
RUN pip install django

当我执行 docker-compose up 时,它们都构建良好,但似乎 db 环境变量没有传递到 django 容器,因为当我运行 os.environ.keys() 在我的 Django 视图之一中,我看不到任何预期的 DB_* 环境变量.mysql 是否需要不同的设置,还是我遗漏了什么.谢谢.

They both build fine when I do docker-compose up but it seems the db environment variables are not passed to the django container since when I run os.environ.keys() in one of my django views I can't see any of the expected DB_* environment variables. So does mysql require a different setup or am I missing something. Thank you.

Docker 撰写版本

Docker compose version

docker-compose version: 1.3.0
CPython version: 2.7.9
OpenSSL version: OpenSSL 1.0.1e 11 Feb 2013

Docker 版本

Docker version 1.6.2, build 7c8fca2

推荐答案

在 Django settings.py 文件中,确保您有以下内容:

In Django settings.py file make sure you have something like:

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'django1',
    'USER': 'django',
    'PASSWORD': 'password', 
    'HOST': 'db',
    'PORT': 3306,
    }
}

然后在您的 docker-compose.yml 文件中确保您有以下内容:

then in your docker-compose.yml file make sure you have something along the lines of:

db:
  image: mysql
  environment:
    MYSQL_ROOT_PASSWORD: docker
    MYSQL_DATABASE: docker
    MYSQL_USER: docker
    MYSQL_PASSWORD: docker

然后根据您所关注的 docker/django 教程,再次运行以下命令以重建所有内容,一切都应该开始工作了

then as per the docker/django tutorial you are following run the following again to rebuild everything and things should start working

docker-compose run web django-admin.py startproject composeexample .

针对进一步的问题,docker在创建新数据库时需要mysql root密码变量.

In response to a further question, the mysql root password variable is required by docker when creating new databases.

在上面的docker-compose中添加了run;查看编辑评论

added run to docker-compose above; see edit comment

相关文章