2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DockerでDjango+MySQLを構築

Posted at

環境

  • macOS Mojava version 10.14.6
  • Docker version 19.03.5

準備

ディレクトリを作成し、Dockerfile, docker-compose.yml, requirements.txtを作成します。

$ mkdir sample
$ cd sample
$ touch {Dockerfile,docker-compose.yml,requirements.txt}

作成したそれぞれのファイルに以下を記述します。

Dockerfile

Dockerfile
FROM python:3
ENV PYTHONBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/

docker-compose.yml

docker-compose.yml
version: '3'
services:
  db:
    image: mysql:5.7
    environment:
      MYSQL_DATABASE: django_db
      MYSQL_ROOT_PASSWORD: root
      MYSQL_USER: user
      MYSQL_PASSWORD: password
      TZ: Asia/Tokyo
    ports:
      - 3306:3306
    volumes:
      - ./mysql:/var/lib/mysql
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

requirements.txt

requirements.txt
Django>=2.0,<3.0
mysqlclient

コンテナの起動

Djangoプロジェクト作成

ターミナル
docker-compose run --rm web django-admin startproject config .

プロジェクトのデータベースの設定

作成したプロジェクトのconfig/settings.pyのデータベースの設定をmysql用に設定。

config/settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_db', # MYSQL_DATABASE
        'USER': 'user', # MYSQL_USER
        'PASSWORD': 'password', # MYSQL_PASSWORD
        'HOST': 'db',
        'PORT': '3306',
    }
}

startapp,migrate

ターミナル
docker-compose run --rm web python manage.py startapp app
docker-compose run --rm web python manage.py migrate

ローカルサーバーの起動

ターミナル
docker-compose up -d

localhost:8000へアクセスし、以下の画面が表示されれば成功です。
スクリーンショット 2019-12-28 13.56.13.png

参考文献

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?