Skip to content

Commit

Permalink
frontend: Create a Django web frontend
Browse files Browse the repository at this point in the history
  • Loading branch information
lucabrunox committed Sep 23, 2024
1 parent 9cc3ac8 commit f7b44d8
Show file tree
Hide file tree
Showing 14 changed files with 276 additions and 4 deletions.
17 changes: 17 additions & 0 deletions .github/workflows/frontend.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Frontend build

on:
push:

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3

- name: Build
shell: bash
working-directory: frontend
run: |
docker build --rm . -t frontend
32 changes: 28 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

This repo contains step-by-step creationg of low-level Terraform + K8s + other stuff for learning purposes.

### Terraform to create a K8s cluster on EC2
### Day 1: Set up Terraform with a remote backend

Define the AWS region that will be used for all the commands:

Expand Down Expand Up @@ -41,15 +41,19 @@ terraform apply \

Use asg_desired_capacity=0 to tear down the cluster.

### Kubernetes single-node cluster on EC2 with kubeadm
### Day 2: Kubernetes single-node cluster on EC2 with kubeadm

Created a raw low-level simple K8s cluster on EC2 on a single master node. Some interesting facts:
Commit: https://github.com/lucabrunox/learning/tree/9cc3ac81d7f835a7de5e69c58378381e20351fdd

Using a raw K8s instead of EKS to learn some low-level details. Some interesting facts:

- It takes 2 minutes and 20 second until all containers are in Running state.
- A t4g.medium is needed to run a cluster. Using a t4g.nano with swap is not enough because the apiserver/etcd will keep timing out.
- CoreDNS and kube-proxy addons are installed by default.
- The advertising IP is coming from `ip route` and it coincides with the private IP of the instance rather than the public one.
- Explanation of flannel networking: https://mvallim.github.io/kubernetes-under-the-hood/documentation/kube-flannel.html
- Explanations of K8s networking:
- https://mvallim.github.io/kubernetes-under-the-hood/documentation/kube-flannel.html
- https://www.redhat.com/sysadmin/kubernetes-pods-communicate-nodes

SSH into the EC2 instance and run crictl and kubectl commands to inspect the cluster:

Expand All @@ -67,3 +71,23 @@ If the cluster is not up check the instance init logs:
```bash
sudo cat /var/log/cloud-init-output.log
```

### Day 3: A Django frontend with GH action to build a Docker image, not deployed yet

Set up following https://docs.djangoproject.com/en/5.1/intro/tutorial01/ with `django-admin startproject mysite`.

The Dockerfile is self-explanatory. To try it out:

```bash
docker run -p 8000:8000 --rm -it $(docker build -q .)
```

Then open http://localhost:8000

To test GH actions I've set up act to run in a Docker, so that it doesn't need to be installed:

```bash
./test_gh.sh
```

Which in turn creates the frontend Docker, yay!
5 changes: 5 additions & 0 deletions act/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
FROM alpine:latest

RUN apk add curl sudo bash

RUN curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/nektos/act/master/install.sh | sudo bash
4 changes: 4 additions & 0 deletions frontend/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
venv
*.sqlite3
__pycache__
.gitignore
3 changes: 3 additions & 0 deletions frontend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
venv
*.sqlite3
__pycache__
17 changes: 17 additions & 0 deletions frontend/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
FROM alpine:latest

WORKDIR /app

RUN set -xe && \
apk add python3 py3-pip tini

COPY requirements.txt .
RUN set -xe && \
python3 -m venv venv && \
source venv/bin/activate && \
pip install -r requirements.txt

COPY . .

ENTRYPOINT ["/sbin/tini", "--"]
CMD ["/app/venv/bin/python", "/app/manage.py", "runserver", "0.0.0.0:8000"]
Empty file added frontend/learning/__init__.py
Empty file.
16 changes: 16 additions & 0 deletions frontend/learning/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for learning project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning.settings')

application = get_asgi_application()
123 changes: 123 additions & 0 deletions frontend/learning/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
"""
Django settings for learning project.
Generated by 'django-admin startproject' using Django 4.2.16.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-m1-fsy+mc4ow6&u%m=t7a7@b6qn6(95o%f)-m$=l+(=71!_3c0'

# 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',
]

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 = 'learning.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 = 'learning.wsgi.application'


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

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


# Password validation
# https://docs.djangoproject.com/en/4.2/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/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
22 changes: 22 additions & 0 deletions frontend/learning/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
URL configuration for learning project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path

urlpatterns = [
path('admin/', admin.site.urls),
]
16 changes: 16 additions & 0 deletions frontend/learning/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for learning project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning.settings')

application = get_wsgi_application()
22 changes: 22 additions & 0 deletions frontend/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == '__main__':
main()
1 change: 1 addition & 0 deletions frontend/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Django==4.2.16
2 changes: 2 additions & 0 deletions test_gh.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/bash
docker run --privileged -v /var/run/docker.sock:/var/run/docker.sock -v .:/workdir -w /workdir --rm $(docker build --rm -q act) act push -P ubuntu-latest=catthehacker/ubuntu:act-latest

0 comments on commit f7b44d8

Please sign in to comment.