Práctica: Django tutorial en Docker
Info previa
Crearemos una imagen de Django tutorial que implantaremos.
Paso 1: Creación de la imagen
Muestro el directorio donde construiremos:
atlas@olympus:~/docker/django-build$ ls -la
total 8
drwxr-xr-x 2 atlas atlas 4096 Jun 20 00:23 .
drwxr-xr-x 22 atlas atlas 4096 Jun 20 00:23 ..
Descarga del código original y cambios
Me bajo el código:
atlas@olympus:~/docker/django-build$ git clone git@github.com:josedom24/django_tutorial.git
Cloning into 'django_tutorial'...
remote: Enumerating objects: 153, done.
remote: Total 153 (delta 0), reused 0 (delta 0), pack-reused 153
Receiving objects: 100% (153/153), 4.25 MiB | 1.59 MiB/s, done.
Resolving deltas: 100% (50/50), done.
atlas@olympus:~/docker/django-build$ ls -la
total 12
drwxr-xr-x 3 atlas atlas 4096 Jun 20 00:26 .
drwxr-xr-x 22 atlas atlas 4096 Jun 20 00:23 ..
drwxr-xr-x 5 atlas atlas 4096 Jun 20 00:27 django_tutorial
En la base del código creo un directorio static
:
atlas@olympus:~/docker/django-build/django_tutorial$ ls -la
total 40
drwxr-xr-x 6 atlas atlas 4096 Jun 20 02:02 .
drwxr-xr-x 3 atlas atlas 4096 Jun 20 01:53 ..
drwxr-xr-x 2 atlas atlas 4096 Jun 20 01:59 django_tutorial
drwxr-xr-x 8 atlas atlas 4096 Jun 20 00:27 .git
-rw-r--r-- 1 atlas atlas 91 Jun 20 00:27 .gitignore
-rw-r--r-- 1 atlas atlas 671 Jun 20 00:27 manage.py
drwxr-xr-x 5 atlas atlas 4096 Jun 20 00:27 polls
-rw-r--r-- 1 atlas atlas 91 Jun 20 00:27 README.md
-rw-r--r-- 1 atlas atlas 7 Jun 20 00:27 requirements.txt
drwxr-xr-x 2 atlas atlas 4096 Jun 20 02:02 static
Personalizo un poco el código, modificando el icono del IESGN en django_tutorial/polls/templates/index.html
. En el body modifico lo siguiente:
<img src="https://64.media.tumblr.com/712c85234ad2f4654b08109761881933/tumblr_otq4duwzAB1voqnhpo2_250.png" alt="DigitalOcean Logo" width="100" />
Modifico settings.py
de la siguiente manera:
"""
Django settings for django_tutorial project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
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/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '9f0h)gozf$g%6igo8&767w1xro0adm+)msxe)!eic$!fhvynb8'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [os.environ.get("ALLOWED_HOSTS")]
# Application definition
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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',
]
ROOT_URLCONF = 'django_tutorial.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'django_tutorial.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ.get("DJANGO_DB_NAME"),
'USER': os.environ.get('DJANGO_DB_USER'),
'PASSWORD': os.environ.get("DJANGO_DB_PASSWORD"),
'HOST': os.environ.get('DJANGO_DB_HOST'),
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
CSRF_TRUSTED_ORIGINS = ['http://*.adrianjaramillo.tk','http://*.127.0.0.1','https://*.adrianjaramillo.tk','https://*.127.0.0.1']
DEFAULT_AUTO_FIELD='django.db.models.AutoField'
Cambios en el directorio base
Creo script.sh
:
#! /bin/sh
sleep 10
python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py createsuperuser --username $DJANGO_SUPERUSER_USERNAME --email $DJANGO_SUPERUSER_EMAIL --noinput
python3 manage.py collectstatic --no-input
python3 manage.py runserver 0.0.0.0:3000
Creo el Dockerfile
:
FROM debian
MAINTAINER Adrián Jaramillo Rodríguez "adristudy@gmail.com"
RUN apt-get update && apt-get install -y python3-pip python3-dev default-libmysqlclient-dev build-essential && apt-get clean && rm -rf /var/lib/apt/lists/*
COPY django_tutorial /usr/share/app
ADD script.sh /usr/share/app
RUN chmod +x /usr/share/app/script.sh
WORKDIR /usr/share/app
RUN pip3 install --no-cache-dir -r requirements.txt
RUN pip3 install mysqlclient
EXPOSE 3000
ENTRYPOINT ["/usr/share/app/script.sh"]
Generación y publicación
Genero:
Publico:
atlas@olympus:~/docker/django-build$ docker push adrianjaramillo/django
Using default tag: latest
The push refers to repository [docker.io/adrianjaramillo/django]
970fc0539140: Pushed
b164ba16140b: Pushed
51a4a55b26c1: Pushed
137e2b7e3cb1: Pushed
1e54713ae38a: Pushed
3c8da5335d03: Pushed
e7597c345c2e: Mounted from adrianjaramillo/bookmedik
latest: digest: sha256:3c398b1701511781690001089f970b4aeb4e4f470df886db19f4adf9595c0b7f size: 1788
Demostraciones paso 1
Repositorio para la generación de la imagen
Imagen generada localmente:
Imagen en Docker Hub:
Paso 2: Despliegue en desarrollo
Muestro el directorio donde lanzaré el escenario:
atlas@olympus:~/docker/django-escenario$ ls -la
total 8
drwxr-xr-x 2 atlas atlas 4096 Jun 20 00:35 .
drwxr-xr-x 23 atlas atlas 4096 Jun 20 00:35 ..
Creo el siguiente docker-compose.yml
:
version: '3.1'
services:
django:
container_name: django
image: adrianjaramillo/django
restart: always
environment:
ALLOWED_HOSTS: "*"
DJANGO_DB_USER: django_user
DJANGO_DB_PASSWORD: django_pass
DJANGO_DB_NAME: django
DJANGO_DB_HOST: django_mariadb
DJANGO_SUPERUSER_USERNAME: admin
DJANGO_SUPERUSER_PASSWORD: admin
DJANGO_SUPERUSER_EMAIL: admin@example.org
ports:
- 8082:3000
depends_on:
- django_db
django_db:
container_name: django_mariadb
image: mariadb
restart: always
environment:
MARIADB_DATABASE: django
MARIADB_USER: django_user
MARIADB_PASSWORD: django_pass
MARIADB_ROOT_PASSWORD: root
volumes:
- django_mariadb_data:/var/lib/mysql
volumes:
django_mariadb_data:
Lanzo los contenedores:
atlas@olympus:~/docker/django-escenario$ docker-compose up -d
Creating network "django-escenario_default" with the default driver
Creating volume "django-escenario_django_mariadb_data" with default driver
Creating django_mariadb ... done
Creating django ... done
Demostraciones paso 2
Repositorio para la creación del escenario
Escenario funcionando:
Django tutorial funcionando:
Paso 3: Puesta en producción en la VPS
Registro DNS
Preparación de Nginx
Configuraré el par de VirtualHosts (HTTP y HTTPS) para Django tutorial.
djangotutorial_http.conf
:
server {
listen 80;
server_name djangotutorial.adrianjaramillo.tk;
return 301 https://$host$request_uri;
}
Lo activo:
djangotutorial_https.conf
:
server {
listen 443 ssl;
server_name djangotutorial.adrianjaramillo.tk;
###################
# RSA certificate #
###################
ssl_certificate /etc/letsencrypt/live/adrianjaramillo.tk/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/adrianjaramillo.tk/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
#############
# Locations #
#############
location / {
proxy_pass http://localhost:8082;
include proxy_params;
}
}
Lo activo:
Reinicio Nginx:
Despliegue de Django tutorial
Clono mi repositorio que tiene el docker-compose.yml
que necesito:
blackmamba@kampe:~/docker$ git clone git@github.com:adriasir123/django-escenario.git
Cloning into 'django-escenario'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 3 (delta 0), pack-reused 0
Receiving objects: 100% (3/3), done.
Me bajo la imagen:
blackmamba@kampe:~/docker/django-escenario$ docker pull adrianjaramillo/django
Using default tag: latest
latest: Pulling from adrianjaramillo/django
e756f3fdd6a3: Already exists
8f5f46ed1055: Pull complete
759268033427: Pull complete
dac2fee9d4d5: Pull complete
b8823c35e13b: Pull complete
d03f9b37dc5f: Pull complete
2741b7f5624c: Pull complete
Digest: sha256:3c398b1701511781690001089f970b4aeb4e4f470df886db19f4adf9595c0b7f
Status: Downloaded newer image for adrianjaramillo/django:latest
docker.io/adrianjaramillo/django:latest
Compruebo que la tengo:
blackmamba@kampe:~/docker/django-escenario$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
adrianjaramillo/django latest d11be0720035 50 minutes ago 548MB
adrianjaramillo/bookmedik v1_2 64141bbe8f9f 8 hours ago 297MB
adrianjaramillo/bookmedik v2 64331ad6b6f9 25 hours ago 496MB
mariadb latest ea81af801379 13 days ago 383MB
Lanzo el escenario:
blackmamba@kampe:~/docker/django-escenario$ docker-compose up -d
Creating network "django-escenario_default" with the default driver
Creating volume "django-escenario_django_mariadb_data" with default driver
Creating django_mariadb ... done
Creating django ... done
Demostraciones paso 3
Django tutorial funcionando: