This guide provides a step-by-step process for deploying a simple Django application on Kubernetes. Each section includes detailed descriptions to ensure better understanding for users at all levels.
1. Set Up a Simple Django Application
This step sets the foundation by creating a basic Django project. You’ll install Django, create a project, and verify it runs correctly locally. This ensures your application is ready for containerization and deployment.
- Install Django:
pip install django
Bash2. Create a new Django project:
django-admin startproject myproject
Bash3. Test the project by running the development server:
python manage.py runserver
BashOpen http://127.0.0.1:8000
in your browser to confirm Django is working. You’ll see a default welcome page indicating the project is ready.
2. Containerize the Django Application
Containerizing the Django app ensures consistent behavior across environments. The Dockerfile specifies the image configuration, including dependencies, working directory, and commands.
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt
COPY . /app/
# Collect static files for Django
RUN python manage.py collectstatic --noinput
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "myproject.wsgi:application"]
DockerfileSteps to Containerize:
- Create a
requirements.txt
file:
django
gunicorn
TeX2. Build the Docker image:
docker build -t django-app:v1 .
BashThis bundles your Django app into a reusable container image tagged as django-app:v1
.
3. Create Kubernetes Deployment and Service
The deployment specifies how your Django app runs on Kubernetes, and the service ensures it is accessible within the cluster.
deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: django-app
spec:
replicas: 2
selector:
matchLabels:
app: django
template:
metadata:
labels:
app: django
spec:
containers:
- name: django
image: django-app:v1
ports:
- containerPort: 8000
YAMLservice.yaml
apiVersion: v1
kind: Service
metadata:
name: django-service
spec:
selector:
app: django
ports:
- protocol: TCP
port: 80
targetPort: 8000
type: ClusterIP
YAMLApply Configurations:
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
YAML4. Add a Database (PostgreSQL)
This step deploys a PostgreSQL database in Kubernetes and configures Django to use it.
postgres-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: postgres
spec:
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:13
env:
- name: POSTGRES_USER
value: django
- name: POSTGRES_PASSWORD
value: password123
- name: POSTGRES_DB
value: django_db
ports:
- containerPort: 5432
YAMLUpdate Django Settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'django_db',
'USER': 'django',
'PASSWORD': 'password123',
'HOST': 'postgres',
'PORT': '5432',
}
}
YAMLApply PostgreSQL Deployment:
kubectl apply -f postgres-deployment.yaml
Bash5. Expose the Application with Ingress
Ingress routes external HTTP/HTTPS traffic to your Django application within the Kubernetes cluster.
ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: django-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: django.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: django-service
port:
number: 80
YAMLApply Ingress Rules:
kubectl apply -f ingress.yaml
Bash6. Enable Persistent Storage for Static Files
Django needs persistent storage for static files (CSS, JavaScript) and media files (user uploads).
persistent-volume.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: django-static-pv
spec:
capacity:
storage: 1Gi
accessModes:
- ReadWriteMany
hostPath:
path: /data/django/static
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: django-static-pvc
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 1Gi
YAMLUpdate Deployment for PVC:
volumeMounts:
- name: django-static
mountPath: /app/static
volumes:
- name: django-static
persistentVolumeClaim:
claimName: django-static-pvc
YAMLApply Persistent Volume:
kubectl apply -f persistent-volume.yaml
Bash7. Best Practices
Adopting best practices ensures a secure, scalable, and efficient Kubernetes deployment:
- Use Secrets for Sensitive Data:
kubectl create secret generic django-secrets --from-literal=DB_PASSWORD=password123
Bash- Monitor Performance: Use tools like Prometheus and Grafana to track app health and metrics.
- Auto-Scale Applications:
kubectl autoscale deployment django-app --cpu-percent=80 --min=2 --max=5
Bash- Add Health Probes:
livenessProbe:
httpGet:
path: /healthz
port: 8000
readinessProbe:
httpGet:
path: /
port: 8000
YAMLConclusion
Deploying Django applications on Kubernetes unlocks the potential for scalability, resilience, and efficient resource management. By containerizing Django, configuring deployments, and leveraging Kubernetes’ powerful orchestration features, teams can ensure their applications are robust and ready to handle real-world demands.
For more insights into deploying Django on Kubernetes, visit the Kubernetes documentation or explore the Django official site. With the right approach and best practices, Kubernetes becomes an invaluable tool for modern Django deployments.