Sunday, June 1, 2025
News PouroverAI
Visit PourOver.AI
No Result
View All Result
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing
News PouroverAI
No Result
View All Result

How to dockerize a Django, Preact, and PostgreSQL Application

February 20, 2024
in Front-Tech
Reading Time: 3 mins read
0 0
A A
0
Share on FacebookShare on Twitter



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 (

An unbeatable tech stack


Preact logo

Running Preact, Django, Postgres, and Docker

{text}

);
}

render(, document.getElementById(‘app’));
“`

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

Tags: ApplicationDjangodockerizePostgreSQLPreact
Previous Post

Interpreting R²: a Narrative Guide for the Perplexed | by Roberta Rocca | Feb, 2024

Next Post

Taxman: Taxman asks FPIs to share info on signatories, justify treaty relief

Related Posts

The essential principles of a good homepage
Front-Tech

The essential principles of a good homepage

June 7, 2024
How to measure and improve user retention
Front-Tech

How to measure and improve user retention

June 6, 2024
Push Animation on Grid Items
Front-Tech

Push Animation on Grid Items

June 5, 2024
How to build a Rails API with rate limiting
Front-Tech

How to build a Rails API with rate limiting

June 4, 2024
Introduction to the B.I.A.S. framework
Front-Tech

Introduction to the B.I.A.S. framework

June 3, 2024
Blue Ridge Ruby is exactly what we need
Front-Tech

Blue Ridge Ruby is exactly what we need

June 3, 2024
Next Post
Taxman: Taxman asks FPIs to share info on signatories, justify treaty relief

Taxman: Taxman asks FPIs to share info on signatories, justify treaty relief

Checkmate with Scale: Google DeepMind’s Revolutionary Leap in Chess AI

Checkmate with Scale: Google DeepMind's Revolutionary Leap in Chess AI

Chinese Stocks Fall as Traders Shrug Off Rate Cut: Markets Wrap

Chinese Stocks Fall as Traders Shrug Off Rate Cut: Markets Wrap

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Trending
  • Comments
  • Latest
Is C.AI Down? Here Is What To Do Now

Is C.AI Down? Here Is What To Do Now

January 10, 2024
Accenture creates a regulatory document authoring solution using AWS generative AI services

Accenture creates a regulatory document authoring solution using AWS generative AI services

February 6, 2024
23 Plagiarism Facts and Statistics to Analyze Latest Trends

23 Plagiarism Facts and Statistics to Analyze Latest Trends

June 4, 2024
Managing PDFs in Node.js with pdf-lib

Managing PDFs in Node.js with pdf-lib

November 16, 2023
From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

June 10, 2024
Turkish Airlines Marketing Strategy: Beyond “Globally Yours”

Turkish Airlines Marketing Strategy: Beyond “Globally Yours”

May 29, 2024
Can You Guess What Percentage Of Their Wealth The Rich Keep In Cash?

Can You Guess What Percentage Of Their Wealth The Rich Keep In Cash?

June 10, 2024
AI Compared: Which Assistant Is the Best?

AI Compared: Which Assistant Is the Best?

June 10, 2024
How insurance companies can use synthetic data to fight bias

How insurance companies can use synthetic data to fight bias

June 10, 2024
5 SLA metrics you should be monitoring

5 SLA metrics you should be monitoring

June 10, 2024
From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

June 10, 2024
UGRO Capital: Targeting to hit milestone of Rs 20,000 cr loan book in 8-10 quarters: Shachindra Nath

UGRO Capital: Targeting to hit milestone of Rs 20,000 cr loan book in 8-10 quarters: Shachindra Nath

June 10, 2024
Facebook Twitter LinkedIn Pinterest RSS
News PouroverAI

The latest news and updates about the AI Technology and Latest Tech Updates around the world... PouroverAI keeps you in the loop.

CATEGORIES

  • AI Technology
  • Automation
  • Blockchain
  • Business
  • Cloud & Programming
  • Data Science & ML
  • Digital Marketing
  • Front-Tech
  • Uncategorized

SITEMAP

  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2023 PouroverAI News.
PouroverAI News

No Result
View All Result
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing

Copyright © 2023 PouroverAI News.
PouroverAI News

Welcome Back!

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Fill the forms bellow to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In