During my recent deep dive into new technologies, I discovered the classic issues of effectively integrating numerous tech tools. I have documented my experiences to help you avoid the challenges I faced. One crucial aspect I explored is utilizing Docker for implementing containerization. Although the initial setup may take a bit longer, it significantly simplifies and optimizes your technological stack.
Prerequisites
To follow this tutorial, ensure you have the following:
– A Django application
– A Preact application
– Docker installed on your system
Getting started
Begin by creating an empty folder named django-preact-docker and navigate to this folder from the terminal. Follow the initial steps of setting up a Django application by creating a virtual environment, activating it, and installing Django. If virtualenv is not installed, run pip install virtualenv. Run the following commands in the terminal:
“`
virtualenv venv
source ./venv/bin/activate
pip install django django-cors-headers psycopg2-binary
“`
Setting Up Django
Navigate to the django-preact-docker folder and create a new Django project named backend by running:
“`
django-admin startproject backend
cd backend
python manage.py runserver
“`
Create a requirements file by running:
“`
pip freeze > requirements.txt
“`
Setting up our Preact application
Head back to the root folder django-preact-docker and create a new Preact application named frontend by running:
“`
npx create-preact-app frontend
cd frontend
npm run dev
“`
Containerizing
Next, create configuration files for Docker to understand how to handle the applications.
Containerize Django
Navigate to django-preact-docker/backend and create a new file named Dockerfile. Add the following content to the file:
“`
# The file may be hidden on Finder; the default macOS shortcut is Shift-Command-. to show hidden files
venv
env
.env
“`
Create a Dockerfile in the backend folder and add the following content:
“`
FROM python:3.8-alpine
ENV PYTHONUNBUFFERED 1
WORKDIR /app/backend
COPY requirements.txt /app/backend/
RUN apk add –update –no-cache postgresql-dev gcc python3-dev musl-dev
RUN pip install -r requirements.txt
COPY . .
CMD [ “python”, “manage.py”, “runserver”, “0.0.0.0:8000” ]
“`
Containerize Preact
Navigate to django-preact-docker/frontend and create a new file named Dockerfile. Add the following content to the file:
“`
node_modules
npm-debug.log
yarn-error.log
“`
Create a Dockerfile in the frontend folder and add the following content:
“`
FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 5173
CMD [“npm”, “run”, “dev”]
“`
Packaging our applications with Docker Compose
Create a configuration file named docker-compose.yml in the django-preact-docker folder. Add the following content to the file:
“`
version: ‘3.9’
services:
db:
image: postgres:14-alpine
ports:
– ‘5432:5432’
environment:
– POSTGRES_PASSWORD=postgres
– POSTGRES_USER=postgres
– POSTGRES_DB=postgres
volumes:
– ./data/db:/var/lib/postgresql/data/
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
– ‘5173:5173’
volumes:
– ./frontend:/app/frontend
depends_on:
– backend
backend:
build:
context: ./backend
dockerfile: Dockerfile
environment:
– POSTGRES_PASSWORD=postgres
– POSTGRES_USER=postgres
– POSTGRES_DB=postgres
ports:
– ‘8000:8000’
volumes:
– ./backend:/app/backend
depends_on:
– db
“`
Build the containers by running:
“`
docker-compose up –build
“`
You can access the servers at the following ports:
– 5173 for frontend
– 8000 for backend
– 5432 for the database
Make sure the servers are running correctly before proceeding. Press Ctrl + C or run `docker-compose down` to stop the containers.
Additional setup
Update the settings in the backend folder by changing settings.py to:
“`
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.postgresql_psycopg2’,
‘NAME’: ‘postgres’,
‘USER’: ‘postgres’,
‘PASSWORD’: ‘postgres’,
‘HOST’: ‘db’,
‘PORT’: ‘5432’,
}
}
“`
Also, modify the CORS settings in settings.py to allow communication across different domains:
“`
INSTALLED_APPS = [
‘corsheaders’, # add this
]
MIDDLEWARE = [
…,
“corsheaders.middleware.CorsMiddleware”,
“django.middleware.common.CommonMiddleware”,
…,
]
CORS_ALLOW_ALL_ORIGINS = True
“`
Testing the stack works together
Create a new file named views.py in backend/backend and add the following code:
“`
from django.http import JsonResponse
def get_text(request):
text = “All operational from the Django backend!”
data = {
‘text’: text,
}
return JsonResponse(data)
“`
Update urls.py to include the new endpoint:
“`
from .views import get_text
urlpatterns = [
# other code
path(‘test/’, get_text),
]
“`
Make a request to http://localhost:8000/test/ to test the Django backend response.
In the frontend, update src/index.jsx to fetch and display the Django response:
“`
import { render } from ‘preact’;
import preactLogo from ‘./assets/preact.svg’;
import ‘./style.css’;
import { useState, useEffect } from ‘react’;
export function App() {
const [text, setText] = useState(null);
useEffect(() => {
fetch(‘http://127.0.0.1:8000/test/’)
.then(res => res.json())
.then(data => {
setText(data.text);
});
});
return (
);
}
render(
“`
Refresh the page to see the updated content and ensure everything is working correctly.
Conclusion
By containerizing your technology stack with Docker, you have taken a significant step towards seamless integration and enhanced efficiency. Despite the initial setup effort, the benefits are evident. With your tech stack containerized, including Django, Preact, and Postgres, you can navigate the tech landscape more effectively. Embrace the possibilities and let your tech journey be characterized by streamlined integration and boundless creativity!
Source link