使用Docker搭建Django的开发环境

docker-compose-django/
├ docker ┬ python ┬ Dockerfile
│        │        └ requirements.txt
│        └ web ─ default.conf
│
├ docker-compose.yml
├ django-project  
├ django-app
├ static
├ templates
└ manage.py

启动web容器、db容器和app容器。
从Dockerfile中创建app容器的映像。

version: '3'
# コンテナ
services:

    # コンテナ1
  web:
    image: nginx:1.17.7
    ports:
      - '80:80'
      # ローカルポート80とDockerポート80を繋げる
    depends_on:
      - app
      # appが立ち上がった後に起動
    volumes:
      - ./docker/web/default.conf:/etc/nginx/conf.d/default.conf
      # ゲストosの./docker/webにあるdefault.confとコンテナ/etc/nginx/conf.dにあるdefault.confと繋げる
      - gunicorn:/var/run/gunicorn
      # ゲストosの現在のディレクトリとコンテナ/var/run/gunicornを繋げる
      - ./static:/static


      # コンテナ2
  app:
    build: ./docker/python
    # imageの代わりに./docker/phpにあるDockerfileからコンテナを作成
    restart: always
    volumes:
      - .:/work
      - gunicorn:/var/run/gunicorn
      - ./static:/work/static

    # nginxを使わない場合portを指定し、pythonのサーバーを起動
    # command: python manage.py runserver 0.0.0.0:8000
    #ports:
    #  - 8000:8000

    depends_on:
      - mysql
      # mysqlが立ち上がった後に起動

      # コンテナ3
  mysql:
    image: mysql:5.7
    environment:
      MYSQL_DATABASE: sample
      MYSQL_USER: user
      MYSQL_PASSWORD: password
      MYSQL_ROOT_PASSWORD: password
      # Mysqlの設定をここに記載する

    ports:
      - "3306:3306"
    volumes:
      - mysql-data:/var/lib/mysql

      # ボリュームを作成
volumes:
  mysql-data:
  gunicorn:
    driver: local
    # mysql-dataというディレクトリをDockerに作成するイメージ
FROM python:3.9-slim
#slimの場合osがubuntu
WORKDIR /work

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
RUN apt-get update && \
    apt-get -y install gcc libmariadb-dev
RUN apt-get install -y nodejs npm
#npmを使うためにインストール
RUN pip install --upgrade pip && pip install pipenv

COPY ./requirements.txt /work/requirements.txt
RUN pip install -r requirements.txt

RUN mkdir -p /var/run/gunicorn
#nginxとgunicornを接続するコマンド
CMD ["gunicorn", "mysite.wsgi", "--bind=unix:/var/run/gunicorn/gunicorn.sock"]
Django==3.0.2
mysqlclient==1.4.6 #mysqlを使う場合に必要
djangorestframework>=3.11.0, <3.12.0
gunicorn==20.0.4
whitenoise==5.2.0
"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 2.1.11.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
    'rest_framework',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [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',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

#詳細はdocker-compose.ymlのenviroment
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'sample',
        'USER': 'user',
        'PASSWORD': 'password',
        # dockerのコンテナ名
        'HOST': 'docker-compose-django_mysql_1',
        'PORT': '3306',
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_URL = '/static/'

upstream gunicorn-django {
    server unix:///var/run/gunicorn/gunicorn.sock;
}

server {
    listen 80;
    server_name localhost;

    location / {
        try_files $uri @gunicorn;
    }
    location @gunicorn {
        proxy_pass http://gunicorn-django;
    }
    # カーレントディレクトリの./staticとnginxのディレクトリ/staticを繋げているので以下のような設定が必要
    location /static {
        alias /static/;
    }
}

现在开始吧。

docker-compose up -d

经常使用的命令。

docker-compose down
docker-compose down --rmi all --remove-orphans
docker exec -it docker-compose-django_app_1 bash
docker exec -it docker-compose-django_app_1 python3 manage.py runserver 0.0.0.0:8000
docker-compose run web python manage.py collectstatic --noinput
mysql -u root -p

因为我认为可能有一些地方是错误的,所以如果您能与我分享,我将非常感激。

bannerAds