1
1

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 composeとmakeでDjango開発環境を半自動化

Last updated at Posted at 2021-07-11

# 目標
1 コマンドで Django アプリケーションの起動・停止が行えるようにする。

1. Dockerfileを書く

ベースは Python の公式イメージ


FROM python

ENV PYTHONUNBUFFERED 1

RUN mkdir /code
WORKDIR /code

ADD requirements.txt /code/
RUN pip install -r requirements.txt

ADD . /code/

2. requirements.txtを書く

ここに書いた Python モジュールが自動でインストールされる。

django
django-cors-headers
django-filter
django-graphql-jwt
graphene_django
djangorestframework
djangorestframework-simplejwt
isodate

3. docker-compose.yml を書く

今回はデフォルトの SQLite を使用するので、 db の指定はしない。

version: "3"
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    env_file: docker-compose.env
    command: python manage.py runserver 0.0.0.0:8000

4. Makefile を書く

前項まででインフラのコード化は終了しているが、migrate や makemigration のコマンドがいちいち長い。(例: docker compose run --rm web python3 ~~~)

だから、make を使ってコマンドを短く省略するとうれしい。

# start up server
up:
	docker compose up

# start up as background task
upd:
	docker compose up -d
	
# stop server
down:
	docker compose down

# access to container's terminal
shell:
	docker compose exec web bash

# create docker image
build:
	docker compose build

service=null
# create new project
startproject:
	docker compose run --rm web python3 manage.py startproject ${service}

# create new app
startapp:
	docker compose run --rm web python3 manage.py startapp ${service}

makemigrations:
	docker compose run --rm web python3 manage.py makemigrations

migrate:
	docker compose run --rm web python3 manage.py migrate

createsuperuser:
	docker compose run --rm web python3 manage.py createsuperuser

これで make ~~ で各種コマンドが使える。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?