🐍
【Python】Dockerで環境構築(windows)[改訂版]
1.ファイル・フォルダ作成
ターミナルにてプロジェクトフォルダの作成
mkdir django_docker_project
cd django_docker_project
VScodeの起動
code .
必要なファイルとディレクトリの一括作成コマンド
必要なファイルとディレクトリを作成
# 作成するファイル名をリストで定義
$files = @(
"Dockerfile",
"docker-compose.yml",
"requirements.txt",
".env",
".env.example",
".gitignore",
".dockerignore",
"README.md",
"LICENSE",
"notes.md",
"setup.cfg",
"Makefile"
)
# 作成するディレクトリ名をリストで定義
$directories = @(
"media",
"static"
"tailwind_app"
)
# ファイルを作成
foreach ($file in $files) {
# ファイルが存在しない場合のみ作成
if (-not (Test-Path $file)) {
New-Item -ItemType File -Path $file -Force | Out-Null
Write-Host "Created file: $file"
} else {
Write-Host "Skipped file (already exists): $file"
}
}
# ディレクトリを作成
foreach ($directory in $directories) {
# ディレクトリが存在しない場合のみ作成
if (-not (Test-Path $directory)) {
New-Item -ItemType Directory -Path $directory -Force | Out-Null
Write-Host "Created directory: $directory"
} else {
Write-Host "Skipped directory (already exists): $directory"
}
}
出力結果
ファイル一括作成完了画面
2.ファイル・フォルダの内容記述
Dockerfileの記述
Dockerfileのファイルの内容
FROM python:3.11-slim
# システムの依存関係をインストール
RUN apt-get update && apt-get install -y \
gcc \
postgresql-client \
curl \
&& rm -rf /var/lib/apt/lists/*
# Node.jsとnpmをインストール(Tailwind CSSの依存関係をインストールするために必要)
RUN curl -sL https://deb.nodesource.com/setup_18.x | bash - \
&& apt-get install -y nodejs \
&& rm -rf /var/lib/apt/lists/*
# 作業ディレクトリを設定
WORKDIR /app
# Pythonの依存関係をインストール
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# プロジェクトファイルをコピー
COPY . .
# Tailwind CSSの依存関係をインストール用の作業ディレクトリ変更
WORKDIR /app/theme/static_src
# package.json がない場合は自動で作成
RUN npm init -y
# Tailwind CSS、PostCSS、Autoprefixer をインストール
RUN npm install -D tailwindcss postcss autoprefixer
# 元の作業ディレクトリに戻る
WORKDIR /app
# 8000番ポートを解放
EXPOSE 8000
# Django開発サーバーを起動
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
.dockerignoreの記載
.dockerignoreのファイルの内容
.dockerignore
node_modules
*.log
.git
__pycache__
*.pyc
.env
postgres_data
*.pyo
*.tmp
*.swp
*.swo
.dockerignore
requirements.txtの記載
requirements.txtのファイルの内容
requirements.txtのファイルの内容
requirements.txtのファイルへの記載
Django
python-dotenv
psycopg2-binary
djangorestframework
django-allauth
django-debug-toolbar
django-extensions
django-tailwind
requests
PyJWT
後からrequirements.txtのファイルの内容を追加した場合
requirements.txtのファイルの内容をインストール
docker-compose exec web pip install -r requirements.txt
requirements.txtへ出力
docker-compose exec web pip freeze > requirements.txt
出力結果
requirements.txtのファイルへバージョンが記載される
asgiref==3.8.1
Django==4.2.17
django-allauth==65.3.0
django-debug-toolbar==4.4.6
django-extensions==3.2.3
django-tailwind==3.8.0
djangorestframework==3.15.2
psycopg2-binary==2.9.10
pydotplus==2.0.2
pyparsing==3.2.0
python-dotenv==1.0.1
sqlparse==0.5.3
パッケージ関連コマンド
django_extensions
django_extensionsでURL一覧を確認するコマンド
docker-compose exec web python manage.py show_urls --format=table
django_extensionsでER図を出力するコマンド
docker-compose exec web python manage.py graph_models -a -o myapp_models.png
django-allauth
django-allauthのtemplateをディレクトリに表示させる
docker-compose exec web bash -c "mkdir -p /app/templates/account && cp -r /usr/local/lib/python3.11/site-packages/allauth/templates/* /app/templates/"
docker-compose.ymlの記載
docker-compose.ymlのファイルの内容
version: '3.8'
services:
db:
image: postgres:15
container_name: db2
environment:
- POSTGRES_DB=${DB_NAME}
- POSTGRES_USER=${DB_USER}
- POSTGRES_PASSWORD=${DB_PASSWORD}
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
web:
build: .
container_name: web2
command: ["python", "manage.py", "runserver", "0.0.0.0:8000"]
volumes:
- .:/app
- ./theme/static_src/package.json:/app/theme/static_src/package.json
- ./theme/static_src/node_modules:/app/theme/static_src/node_modules
ports:
- "8000:8000"
depends_on:
- db
environment:
- DEBUG=${DJANGO_DEBUG}
- DATABASE_NAME=${DB_NAME}
- DATABASE_USER=${DB_USER}
- DATABASE_PASSWORD=${DB_PASSWORD}
- DATABASE_HOST=${DB_HOST}
- DATABASE_PORT=${DB_PORT}
volumes:
postgres_data:
.envの記載
.envのファイルの内容
.env
DJANGO_DEBUG=false
DB_NAME=name
DB_USER=myprojectuser
DB_PASSWORD=mypassword
DB_HOST=db
DB_PORT=5432
.env.example
DEBUG=True
DATABASE_NAME=my_local_db
DATABASE_USER=my_local_user
DATABASE_PASSWORD=my_local_password
DATABASE_HOST=localhost
DATABASE_PORT=5432
.gitignoreの記載
.gitignoreのファイルの内容
# Python files
*.pyc
*.pyo
__pycache__/
# Django-specific
db.sqlite3
*.log
*.pot
*.mo
media/
static/
# Virtual environment
env/
venv/
.env/
tox/
nox/
.coverage/
# IDE/editor config
.idea/
.vscode/
.pytest_cache/
# Environment variables
.env
.env.*
# Other generated files
*.bak
*.swp
*.swo
*.db-journal
.node_modules/
Makefileの記載(※:WslやChocolateyでインストールする必要有)
Makefileの記載
# サービスの起動
up:
docker-compose up --build
# サービスの停止
down:
docker-compose down
# サービスの再起動
restart:
docker-compose down
docker-compose up --build
# データベースのマイグレーション
migrate:
docker-compose exec web python manage.py migrate
# Djangoアプリケーションの作成
startapp:
docker-compose exec web python manage.py startapp $(name)
# 管理者ユーザーの作成
createsuperuser:
docker-compose exec web python manage.py createsuperuser
# 静的ファイルの収集
collectstatic:
docker-compose exec web python manage.py collectstatic --noinput
# テストの実行
test:
docker-compose exec web pytest
Django admin
の導入とマイグレーションの実行
3.Django adminに必要なコマンド一覧
プロジェクトフォルダの作成(プロジェクト初期化用のコマンドを実行)
docker run --rm -v ${PWD}:/app -w /app python:3.11-slim bash -c "pip install django && django-admin startproject <project_name> ."
出力結果
プロジェクトフォルダの作成(プロジェクト初期化用のコマンドを実行)
$ docker run --rm -v ${PWD}:/app -w /app python:3.11-slim bash -c "pip install django && django-admin startproject project_name ."
Collecting django
Downloading Django-5.1.4-py3-none-any.whl.metadata (4.2 kB)
Collecting asgiref<4,>=3.8.1 (from django)
Downloading asgiref-3.8.1-py3-none-any.whl.metadata (9.3 kB)
Collecting sqlparse>=0.3.1 (from django)
Downloading sqlparse-0.5.3-py3-none-any.whl.metadata (3.9 kB)
Downloading Django-5.1.4-py3-none-any.whl (8.3 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 8.3/8.3 MB 11.1 MB/s eta 0:00:00
Downloading asgiref-3.8.1-py3-none-any.whl (23 kB)
Downloading sqlparse-0.5.3-py3-none-any.whl (44 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 44.4/44.4 kB 1.0 MB/s eta 0:00:00
Installing collected packages: sqlparse, asgiref, django
Successfully installed asgiref-3.8.1 django-5.1.4 sqlparse-0.5.3
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
[notice] A new release of pip is available: 24.0 -> 24.3.1
[notice] To update, run: pip install --upgrade pip
マイグレーションの実行
docker-compose exec web python manage.py migrate
出力結果
出力結果
$ docker-compose exec web python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
管理者ユーザー(admin)の作成
docker-compose exec web python manage.py createsuperuser
出力結果
$ docker-compose exec web python manage.py createsuperuser
ユーザー名 (leave blank to use 'root'): admin
メールアドレス: test@test.com
Password:
Password (again):
Superuser created successfully.
4.コンテナの起動
docker-compose up --build
5.アプリケーションフォルダの作成
アプリケーションフォルダ作成1
<app_name>アプリケーションフォルダの作成(自由に命名可能)
docker-compose exec web python manage.py startapp <app_name>
出力結果
settings.py
の記述
6.settings.pyの設定
SECURITY WARNING(※記載部分に追加)
# SECURITY WARNING
import os
DEBUG = True
ALLOWED_HOSTS = []
INTERNAL_IPS = [
'127.0.0.1',
]
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': lambda request: True,
'HIDE_DJANGO_SQL': False,
}
settings.pyの設定
INSTALLED_APPS(※記載部分に追加)
INSTALLED_APPS = [
...
'<app_name>', # 追加
'debug_toolbar', # 追加
'django_extensions', # 追加
'tailwind', # 追加
'django.contrib.sites', # 追加
'allauth', # 追加
'allauth.account', # 追加
'allauth.socialaccount', # 追加
'allauth.socialaccount.providers.google', # 追加
]
SITE_ID = 1 # 必須
settings.pyの設定
ミドルウェアに必要な記述を行う(※記載部分に追加)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware', # 追加
'allauth.account.middleware.AccountMiddleware', # 追加
]
settings.pyの設定
データベース設定(※記載部分に上書き)
from dotenv import load_dotenv
load_dotenv()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.getenv('DATABASE_NAME', 'default_db'),
'USER': os.getenv('DATABASE_USER', 'default_user'),
'PASSWORD': os.getenv('DATABASE_PASSWORD', ''),
'HOST': os.getenv('DATABASE_HOST', 'localhost'),
'PORT': os.getenv('DATABASE_PORT', '5432'),
}
}
settings.pyの設定
画像・動画の設定(※記載部分に追加および上書き)
# Static files
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'theme', 'static'),
]
# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
settings.pyの設定
言語・時間の設定(※記載部分に上書き)
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'
USE_I18N = True
USE_TZ = True
settings.pyの設定
settings.pyのINSTALLED_APPSを新規追加
# allauth
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
settings.pyの設定
settings.pyへ以下を新規追加
# login & email settings
LOGIN_URL = '/accounts/login/'
ACCOUNT_LOGOUT_REDIRECT_URL = '/'
ACCOUNT_EMAIL_VERIFICATION = "none"
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_EMAIL_REQUIRED = True
settings.pyの設定
settings.pyのDIRSへ以下を追加
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'), # 追加
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
url.py
の設定
7.urls.pyの設定(※記載部分に上書き)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('__debug__/', include('debug_toolbar.urls', namespace='djdt')),
path('accounts/', include('allauth.urls')),
]
Tailwindcss
の設定
8.8-1:Tailwindcssの設定1
settings.pyのINSTALLED_APPSの追加(※記載部分に追加)
INSTALLED_APPS = [
...
'<app_name>',
'debug_toolbar',
'django_extensions',
'tailwind',
'theme', # 追加
]
# App
TAILWIND_APP_NAME = 'theme' # 追加
アプリケーションフォルダ作成2
tailwindcss用アプリケーションフォルダの作成
docker-compose exec web python manage.py tailwind init
出力結果
8-2:Tailwindcssの設定2
npm installを行い、node_modulesとpackage.json.lockが生成される
docker-compose exec -w /app/theme/static_src web npm install
8-3:Tailwindcssの設定3
buildを行い、static/css/distフォルダの中にstyle.cssファイルが作成される
docker-compose exec -w /app/theme/static_src web npm run build
8-4:Tailwindcssの設定4
Djangoのコマンドで、静的ファイル(CSS、JavaScriptなど)を集めて、STATIC_ROOTで指定したディレクトリにコピーする
docker-compose exec web python manage.py collectstatic
8-5:Tailwindcssの設定5
tailwind.config.jsに以下を追加
module.exports = {
content: [
/**
* HTML. Paths to Django template files that will contain Tailwind CSS classes.
*/
'./templates/**/*.html', # 追加
9.ブラウザ表示確認
ブラウザで以下のURLにアクセスし、ブラウザの表示を確認
http://localhost:8000/admin
出力結果
コンテナ起動成功ログ
> docker-compose up
[+] Running 2/2
✔ Container test-python-db-1 Running 0.0s
✔ Container test-python-web-1 Created 1.3s
Attaching to db-1, web-1
web-1 | Watching for file changes with StatReloader
v View in Docker Desktop w Enable Watch
Djcango-adminのログイン画面
ブラウザで以下のURLにアクセスし、ブラウザの表示を確認
http://localhost:8000/accounts/login/
Djcango-allauthのログイン画面
Discussion