[PYTHON] Create a django environment with docker-compose (MariaDB + Nginx + uWSGI)

Introduction

This is the first post of qiita. If you find something wrong, I would appreciate it if you could comment ~ Partially modified on 2019/12/18

I'm using Pycharm.

directory

The directory looks like this

.
├── db
│   ├── data
│   └── sql
│       └── init.sql
├── docker-compose.yml
├── nginx
│   ├── conf
│   │   └── app_nginx.conf
│   ├── log
│   └── uwsgi_params
├── python
│   ├── Dockerfile
│   └── requirements.txt
├── src
│   └── project
│       ├── app
│       ├── project
│       └── manage.py
│       └── uwsgi.ini
└── static

Database

Use MariaDB. Create a data folder and init.sql for initialization in the db directory.

CREATE DATABASE IF NOT EXISTS app CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE USER IF NOT EXISTS 'root'@'%' IDENTIFIED BY 'root';
GRANT ALL PRIVILEGES ON app.* TO 'app'@'%';

FLUSH PRIVILEGES;

When you post it on github, put it in .gitigonre so that you can not see the password etc.
Do not create a dockerfile, but write it in docker-compose.yml.

Nginx

It skips static files such as images to nginx, which is a reverse proxy server.

app_nginx.conf

upstream django {
    ip_hash;
    server python:8001;
}

# configuration of the server
server {
    # the port your site will be served on
    listen      8000;
    # the domain name it will serve for
    server_name 127.0.0.1; # substitute your machine's IP address or FQDN
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;   # adjust to taste

    location /static {
        alias /static;
    }


    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed
    }
}

First, if there is access, it will be received on nginx port 8000, if there is access to the static file static, it will be skipped to nginx static, which is a reverse proxy server, and the others will be skipped to the application server (uWSGI) on port 8001.

uwsgi_params

uwsgi_param  QUERY_STRING       $query_string;
uwsgi_param  REQUEST_METHOD     $request_method;
uwsgi_param  CONTENT_TYPE       $content_type;
uwsgi_param  CONTENT_LENGTH     $content_length;

uwsgi_param  REQUEST_URI        $request_uri;
uwsgi_param  PATH_INFO          $document_uri;
uwsgi_param  DOCUMENT_ROOT      $document_root;
uwsgi_param  SERVER_PROTOCOL    $server_protocol;
uwsgi_param  REQUEST_SCHEME     $scheme;
uwsgi_param  HTTPS              $https if_not_empty;

uwsgi_param  REMOTE_ADDR        $remote_addr;
uwsgi_param  REMOTE_PORT        $remote_port;
uwsgi_param  SERVER_PORT        $server_port;
uwsgi_param  SERVER_NAME        $server_name;

params is ok with copy

python

Dockerfile/python


# The first instruction is what image we want to base our container on
# We Use an official Python runtime as a parent image
FROM python:3.8-alpine
# The enviroment variable ensures that the python output is set straight
# to the terminal with out buffering it first
ENV PYTHONUNBUFFERED 1
ENV PYTHONIOENCODING utf-8
ENV APP_PATH  code
# Set the working directory to /code
WORKDIR /$APP_PATH
COPY ./requirements.txt /$APP_PATH
# Install any needed packages specified in requirements.txt
RUN apk add --no-cache --virtual .build-deps bash gcc musl-dev libffi-dev \
 g++ libgcc libstdc++ libxml2-dev libxslt-dev openssl-dev curl \
 && apk add --no-cache --virtual --update-cache\
 jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \
 mariadb-dev mariadb-connector-c-dev \
 && pip install cython && pip install -U pip && pip install -r requirements.txt
 # Make alpine lighter
RUN rm -rf /var/cache/apk/* && \
    rm -rf /tmp/*

Installation error occurs frequently depending on line breaks and delimiters when apk add is performed Since it worked, the current situation is okay, so ...

Django==3.0
flake8==3.7.9
ipython==7.10.1
mysqlclient==1.4.6
Pillow==6.2.1
uWSGI==2.0.18

I also include flake8, which checks the code, and ipython, which has a powerful interpreter for python. There are several drivers for database connections, but we use the officially recommended mysqlclient. https://docs.djangoproject.com/ja/3.0/ref/databases/#mysql-db-api-drivers

docker-compose.yml


version: '3.4'
services:
  nginx:
    image: nginx:1.13
    container_name: app_nginx
    ports:
      - "8000:8000"
    volumes:
      - ./nginx/conf:/etc/nginx/conf.d
      - ./nginx/uwsgi_params:/etc/nginx/uwsgi_params
      - ./static:/static
      - ./nginx/log:/var/log/nginx
    depends_on:
      - python
  db:  # the same name as 'host' in DATABASES setting, otherwise Django won't find the database
    image: mariadb:10.1
    container_name: app_mariadb
    ports:
      - 3306:3306
    environment:
      MYSQL_DATABASE: app
      MYSQL_ROOT_USER: root
      MYSQL_ROOT_PASSWORD: root
      TZ: 'Asia/Tokyo'
    volumes:
      - ./db/data:/var/lib/mysql
      - ./db/sql:/docker-entrypoint-initdb.d
  python:
    build: ./python
    image: python_blog
    container_name: app_python
    command: uwsgi --ini /code/project/uwsgi.ini
    volumes:
      - ./src:/code
      - ./static:/static
    expose:
      - "8001"
    depends_on:
      - db 

Match the service name db with the host db in the django settings.py db settings.


If you go this far Where docker-compose.yml is

$ docker-compose up -d --build

Let's start the container. nginx and python container won't start.


command: uwsgi --ini /code/project/uwsgi.ini

I don't have uwsgi.ini yet, so create a django project and place it.

$ docker-compose run --rm python django-admin.py startproject project

Create a django project. The python part is the service name of docker-compose.yml If you don't add --rm, many python containers will be created, so delete them every time you run.

[uwsgi]
socket = :8001
module = project.wsgi
wsgi-file = /code/project/project/wsgi.py
logto = /code/project/project/uwsgi.log
chdir=/code/project
py-autoreload = 1

Place uwsgi.ini

$ docker-compose down
$ docker-compose up -d
$ docker ps -a

All containers seem to be up

$ docker exec -it app_python /bin/bash
$ cd ./project/
$ python manage.py startapp app

The python environment is made with alpine linux, and bash is not included in alpine, so / bin / sh or / bin / ash. This time I put bash so bash Make a django app

Settings in django

settings.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app.apps.AppConfig',  #add to


#Change
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'app',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'db',
        'PORT': '3306',
        'OPTIONS': {
            'charset': 'utf8mb4',
        },
    }

#Change to your liking
LANGUAGE_CODE = 'ja'

TIME_ZONE = 'Asia/Tokyo'


STATIC_ROOT = './../../../static/'  #Omoto for distribution for production environment
STATIC_URL = '/static/'  #Url used in production environment

# Custom Useer
AUTH_USER_MODEL = 'app.User'

According to the official, before migrating, I have created a custom user for the time being. Create a custom user https://docs.djangoproject.com/ja/3.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project

models.py

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
	pass

admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .models import User

admin.site.register(User, UserAdmin)

In the docker container

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py createsuperuser

http://localhost:8000/ django should be up If there is an error in the server, try docker-compose up again

After migrating, create a user for django admin http: // localhost: 8000 / admin / Access djangoadmin Since I am using uwsgi, css is not working


$ python manage.py collectstatic

django admin also has css

You should now be able to develop. .. ..

reference

Docker-Compose with Python3.6 + NGINX + MariaDB10 + uWSGI's Django environment greedy set

Recommended Posts

Create a django environment with docker-compose (MariaDB + Nginx + uWSGI)
Create Nginx + uWSGI + Python (Django) environment with docker
Django development environment construction with Docker-compose + Nginx + uWSGI + MariaDB (macOS edition)
Build a Django development environment with Docker! (Docker-compose / Django / postgreSQL / nginx)
Create Python + uWSGI + Nginx environment with Docker
Create a development environment for Go + MySQL + nginx with Docker (docker-compose)
Create a homepage with django
Create a virtual environment with Python!
Create a file uploader with Django
Initial setting of environment using Docker-compose + Django + MySQL + Nginx + uwsgi
Create a Todo app with Django ① Build an environment with Docker
[Python] Create a virtual environment with Anaconda
Build a Fast API environment with docker-compose
Create a virtual environment with Python_Mac version
I made a development environment for Django 3.0 with Docker, Docker-compose, Poetry
[DynamoDB] [Docker] Build a development environment for DynamoDB and Django with docker-compose
Create a Python3.4 + Nginx + uWSGI + Flask Web application execution environment with haste using pyenv on Ubuntu 12.04
Build Django + NGINX + PostgreSQL development environment with Docker
Build the fastest Django development environment with docker-compose
Start Django in a virtual environment with Pipenv
Create a virtual environment with conda in Python
[Python] Build a Django development environment with Docker
Create a python3 build environment with Sublime Text3
Build a Django environment with Vagrant in 5 minutes
Create a dashboard for Network devices with Django!
Build a Django development environment with Doker Toolbox
Create a one-file hello world application with django
Quickly build a Python Django environment with IntelliJ
Create a Django schedule
Python environment with docker-compose
Create a Python environment
A memo to create a virtual environment (venv) before Django
Create a Todo app with Django REST Framework + Angular
I tried to create a table only with Django
Create a web application execution environment of Python3.4 + Nginx + uWSGI + Flask with haste using venv on Ubuntu 14.04 LTS
Create a virtual environment with Anaconda installed via Pyenv
Create a python development environment with vagrant + ansible + fabric
code-server Online environment (2) Create a virtual network with Boto3
Launch Django on a Docker container with docker-compose up
Create a Japanese OCR environment with Anaconda (tesseract + pyocr)
Remote debug Django environment created with docker-compose with VS Code
Build a development environment with Poetry Django Docker Pycharm
Build a Django environment for Win10 (with virtual space)
Create a machine learning environment from scratch with Winsows 10
Create an environment with virtualenv
Minimal website environment with django
Create an API with Django
API with Flask + uWSGI + Nginx
Create a heatmap with pyqtgraph
Create a directory with python
Try running python in a Django environment created with pipenv
[Memo] Build a development environment for Django + Nuxt.js with Docker
[Django] Build a Django container (Docker) development environment quickly with PyCharm
Create a web API that can deliver images with Django
Deploy a Django application on EC2 with Nginx + Gunicorn + Supervisor
Create a social integration API for smartphone apps with Django
[Python] Create a screen for HTTP status code 403/404/500 with Django
Building a kubernetes environment with ansible 2
Build FastAPI + uvicorn + nginx with docker-compose
Create a Python execution environment for Windows with VScode + Remote WSL
Steps to create a Django project