LoginSignup
0
0

DjangoチュートリアルのためのDocker環境構築

Last updated at Posted at 2023-07-28

※ Djangoはじめてなので指摘あれば歓迎します

やりたいこと

Djangoのチュートリアルやりたい
そのために

  • Djangoの環境構築
  • Dockerでの環境

依存関係も管理されていてほしいのでpoetryというパッケージ管理ツールを利用します
0ベーススタートです

最終的な構成

├── docker
│   ├── app
│       └── Dockerfile
├── docker-compose.yml
├── poetry.lock
├── pyproject.toml
└── src
    ├── manage.py
    └── mysite
        ├── __init__.py
        ├── asgi.py
        ├── settings.py
        ├── urls.py
        └── wsgi.py

Docker環境作成

まず、作業ディレクトリに

docker/app/Dockerfileを作成します

FROM python:3.11

ENV PYTHONUNBUFFERED 1

WORKDIR /workspace

# poetryインストール
RUN curl -sSL https://install.python-poetry.org | python3 -
RUN echo 'export PATH="/root/.local/bin:$PATH"' >> ~/.bashrc && . ~/.bashrc && poetry config virtualenvs.create false

ADD . /workspace/

Python環境をセットアップし、Pythonのパッケージ管理ツールであるPoetryをインストール。
PYTHONUNBUFFEREDは標準出力のバッファリングを無効にして、すぐにコンソールに出力されるようにする。

つぎに作業ディレクトリ直下にdocker-compose.ymlを作成します

version: '3.8'

services:
  app:
    build: 
      context: ./docker/app
      dockerfile: Dockerfile
    volumes:
      - .:/workspace
    working_dir: /workspace/src
    ports:
      - 8000:8000
    tty: true

docker-compose up -dしてdocker-compose exec app bashしてコンテナに入ります。

Djangoのセットアップ

まずコンテナに入ると/workspace/srcにいるのでcd ..して一段上に。

poetry initを実行します

 poetry init

Package nameとAuthorだけ入れて、enterしておけばできます。

This command will guide you through creating your pyproject.toml config.

Package name [workspace]: app
Version [0.1.0]:  
Description []:  
Author [None, n to skip]:  n
License []:  
Compatible Python versions [^3.11]:  

Would you like to define your main dependencies interactively? (yes/no) [yes] 
You can specify a package in the following forms:
  - A single name (requests): this will search for matches on PyPI
  - A name and a constraint (requests@^2.23.0)
  - A git url (git+https://github.com/python-poetry/poetry.git)
  - A git url with a revision (git+https://github.com/python-poetry/poetry.git#develop)
  - A file path (../my-package/my-package.whl)
  - A directory (../my-package/)
  - A url (https://example.com/packages/my-package-0.1.0.tar.gz)

Package to add or search for (leave blank to skip): 

Would you like to define your development dependencies interactively? (yes/no) [yes] 
Package to add or search for (leave blank to skip): 

そしてdjangoをインストールします

poetry add django

この時点で以下のような構成です。

├── docker
│   └── app
│       └── Dockerfile
├── docker-compose.yml
├── poetry.lock
├── pyproject.toml
└── src

あとは以下のコマンドでdjangoのプロジェクト作成します。

django-admin startproject mysite ./src

srcに移動して、サーバーを起動

cd src
python manage.py runserver 0:8000

localhost:8000にアクセスして画面出れば完了

django.png

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