How to build a Django (python) environment on docker

How to build a Django (python) environment on docker

A summary of the procedure for creating a project and application using Django on docker and displaying it on the browser using the development server.

procedure

  1. [Create PJ directory](Create #pj directory)
  2. [Create requirements.txt file](Create #requirementstxt file)
  3. [Create docker file](Create docker file)
  4. [Create docker-compose.yml](Create docker compose yml)
  5. Create a container from a config file (create a container from a config file)
  6. [Edit settigs.py](Edit settigspy)
  7. [Start Container](Start Container)
  8. [Create app](Create app)
  9. Edit views.py (Edit viewspy)
  10. Create and edit urls.py (create and edit urlspy)

> Referenced sites ・ [Create Docker official Django](https://docs.docker.com/compose/django/) -[Django Official First App Creation](https://docs.djangoproject.com/ja/3.1/intro/tutorial01/)

Creating a PJ directory

mkdir django
cd django

Creating a requirements.txt file

Create a file that specifies the package to install.

touch requirements.txt

requirements.txt


Django>=3.0,<4.0
psycopg2-binary>=2.8

Install Django and Psycopg.

Psycopg is a tool for using PostgreSQL efficiently. -binary is an OS-only language version, so no compilation is required.

Creating a docker file

Create a dockerfile to create an image of python3.

touch dockerfile

dockerfile


FROM python:3
ENV PYTHONUNBUFFERED=1
RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/

From image name Pull the specified image from docker hub. (Find local if not on dockerhub)

・ ʻENV variable name` Setting environment variables. Put 1 in the variable PYTHONUNBUFFERED. Make console standard output (stdout) and standard error output (stderr) output immediately when an error occurs (disable buffer, same as python's -u option)

PYTHONUNBUFFERED


-`RUN command` Create a directory called / code in the container

WORKDIR directory Makes the specified directory (/ code) the root directory

· COPY host container Copy the host requirements.txt under / code / of the container

· Pip install -r file path Install the package written in the specified file.

The file generally uses requirements.txt. 「-r」 = 「--requirement」


## Create docker-compose.yml Create a docker-compose file to create the image. A file for creating an image containing multiple containers. (dockerfile is only one container)
touch docker-compose.yml

docker-compose.yml


version: "3.8"
   
services:
  db:
    image: postgres
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8100:8000"
    depends_on:
      - db

Prepare two containers in the image.

Version:" 3.8 " Specify the version of the description method of docker-compose.yml. It is necessary to specify because the writing method differs depending on the version.

Services The container to create. Create two, db and web.

・ ʻImages` Specify the image to use. Create a container by pulling postgres from docker hub.

・ ʻEnvironment` Set environment variables. Set DB to postgres. The user name and PW are optional.

· Build directory path Create a container from the dockerfile in the specified directory.

If no file name is specified, select docker file. If you have a different name, specify the file name as well.

Command A command to execute inside a container. Start the server at localhost: 8000.

Run runserver in manage.py. manage.py is a command line utility. Import useful commands.

· Volumes: -Host: Container Link (mount) the host directory with the specified directory in the container.

The project folder on the host and / code in the container are synchronized. ** For files that you do not want to synchronize, create .dockerignore ** and describe the file / folder name.


· `Ports:-"Host: Container" ` Connect the port on the host side to the specified port on the container side.

Accessing localhost: 8100 connects to port 8000 in the container.

Depends_on Connect the web container to the db container. Previously, link was used, but v2.0 and above can be connected to the container in docker-compose.yml via a network without any special description. (Does depend_on unnecessary?)


## Create a container from a config file
docker-compose run web django-admin startproject mysite

-Docker-compose run [service name] [command] Create a container with the specified service name and execute the command.

Create an image based on the docker-comopse.yml file in the executed folder, create a container, and start it all at once.

Here, start the web service.

· Django-admin startporject PJ name Create a PJ.

A directory is created with the specified PJ name (mysite).

File to be created


mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

## Editing settigs.py Write DB settings to mysite / settings.py. Since sqlite3 is specified in the initial setting, overwrite it.

mysite/settings.py


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}

(Reference) Default description


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

## Start container
docker-compose up

abridgement
web_1  | Django version 3.1.2, using settings 'mysite.settings'
web_1  | Starting development server at http://0.0.0.0:8100/
web_1  | Quit the server with CONTROL-C.

Start the created container.

The specified server starts up. To see the status, open another bash window and run docker ps.

$ docker ps
CONTAINER ID        IMAGE                       COMMAND                  CREATED             STATUS              PORTS                                            NAMES
9615ecd4098f        django_web                  "python manage.py ru…"   16 minutes ago      Up About a minute   0.0.0.0:8100->8000/tcp                           django_web_1

If you want it to start in the background, use ʻup -d`.

You can open the page by accessing localhost: 8100 (you can access loaclhost: 8000 in the container)

image.png


## Create app Go inside the container and create an app.
##Launch bash in a running container
$ docker exec -it django_web_1 bash
root@faef5f41e1c7


##Creating a django app
root@faef5f41e1c7:/code# python manage.py startapp polls


##Check the folder
root@faef5f41e1c7:/code# ls
Dockerfile  docker-compose.yml	manage.py  mysite  polls  requirements.txt

Succeeded in creating polls in the container. A directory is also created on the host side. (Because volume is specified and synchronized)

image.png

Difference between project and app

I'm running similar commands, startproject and startapp, with django commands.

django-admin startproject mysite python manage.py startapp polls

There is only one project, and there can be multiple apps.

Only one app called polls is created in the project called mysite.


## Edit views.py Edit views.py in the polls folder you created earlier to control the screen display.

Since the editor is not installed in the container, exit the container once.

root@faef5f41e1c7:/code# exit

▼ Write a program that displays "Hello, This is Django Polls" on the screen.

polls/views.py


from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, This is Django Polls")

## Creating and editing urls.py It is necessary to set the URL in polls and the url as a project.

polls/urls.py


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

mysite/urls.py


from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

Recognize polls urls.py as path and make it accessible with polls /.

After writing, load the page with localhost: 8100 / polls.

image.png

The display is completed successfully.

Recommended Posts

How to build a Django (python) environment on docker
How to build a Python environment on amazon linux 2
How to build a new python virtual environment on Ubuntu
[Python] Build a Django development environment with Docker
How to build a Python environment using Virtualenv on Ubuntu 18.04 LTS
Build a python3 environment on CentOS7
How to run a Django application on a Docker container (development and production environment)
How to build a python2.7 series development environment with Vagrant
How to build a sphinx translation environment
Build a python environment on MacOS (Catallina)
I want to build a Python environment
Build a Python + OpenCV environment on Cloud9
How to build a beautiful Python environment on a new Mac and install Jupter Notebook
# 3 Build a Python (Django) environment on AWS EC2 instance (ubuntu18.04) part2
Learn how to use Docker through building a Django + MySQL environment
Build a LAMP environment on your local Docker
How to create a Python virtual environment (venv)
Simply build a Python 3 execution environment on Windows
[Latest] How to build Java environment on Ubuntu
Build a python environment with ansible on centos6
Build a Python environment on Mac (Mountain Lion)
Build a Python development environment on your Mac
How to build Java environment on Ubuntu (Linux)
Quickly build a Python Django environment with IntelliJ
Build a Python development environment on Raspberry Pi
Build a Python + bottle + MySQL environment with Docker on RaspberryPi3! [Easy construction]
Build Python environment on Windows
Build python environment on windows
Build a Python environment offline
Build a GVim-based Python development environment on Windows 10 (3) GVim8.0 & Python3.6
Build a Django development environment using pyenv-virtualenv on Mac
How to set up a Python environment using pyenv
# 2 Build a Python environment on AWS EC2 instance (ubuntu18.04)
How to deploy a Django application on Alibaba Cloud
Build a machine learning Python environment on Mac OS
Build a GVim-based Python development environment on Windows 10 (1) Installation
Build a Python development environment on Mac OS X
Build a Python virtual environment using venv (Django + MySQL ①)
[Go + Gin] I tried to build a Docker environment
Build a Python environment on your Mac using pyenv
How to build a development environment for TensorFlow (1.0.0) (Mac)
Build a Python development environment using pyenv on MacOS
How to use Django on Google App Engine / Python
How to run Django on IIS on a Windows server
Build a development environment with Poetry Django Docker Pycharm
How to build an environment for using multiple versions of Python on Mac
Build a Python + bottle + MySQL environment with Docker on RaspberryPi3! [Trial and error]
docker build python based on alpine
Building a Python environment on Mac
How to write a Python class
Build a go environment using Docker
Create a Python environment on Mac (2017/4)
Build Mysql + Python environment with docker
Create a python environment on centos
How to delete a Docker container
Build Python 3.8 + Pipenv environment on Ubuntu 18.04
Build a python machine learning study environment on macOS sierra
A memo on how to easily prepare a Linux exercise environment
Build a Django development environment with Docker! (Docker-compose / Django / postgreSQL / nginx)
[Memo] Build a development environment for Django + Nuxt.js with Docker
Don't lose to Ruby! How to run Python (Django) on Heroku