Easy steps for Django application deployment using Kubernetes

Savita ShelarSavita Shelar
6 min read

Kubernetes containerization is the process of packaging and deploying applications in containers using the Kubernetes platform. Containers are lightweight, isolated, and portable environments that allow you to run your applications consistently across different environments.

Here are the steps to containerize and deploy your application using Kubernetes:

  1. Create namespace for application.

    In Kubernetes, a namespace is a way to organize and isolate resources within a cluster. A namespace provides a virtual cluster within a physical cluster, allowing multiple teams or projects to share the same physical resources while keeping their resources separate and isolated from each other.

     kubectl create namespace django-todo-ns
    
  2. Choose a containerization technology.

    There are several containerization technologies available, such as Docker, Containerd, and CRI-O. Choose the containerization technology that best suits your needs.

  3. Create a Dockerfile.

    A Dockerfile is a script that contains instructions for building a Docker image of your application. The Dockerfile specifies the base image, dependencies, environment variables, and other configuration options for your application.

    Here's an example of a simple Dockerfile:

     FROM python:3
     RUN pip install django==3.2
     COPY . .                                                                                                                                                
     RUN python manage.py migrate
     EXPOSE 8000
     CMD ["python","manage.py","runserver","0.0.0.0:8000"]
    

    This Dockerfile creates a Docker image based on the Python 3.9 image, installs the dependencies specified in requirements.txt, and runs the app.py file when the container starts.

  4. Build the Docker image.

    Use the docker build command to build the Docker image from the Dockerfile.

     docker build -t django-todo-app:latest .
    

    This command builds the Docker image with the tag "django-todo-app" and the "latest" version.

  5. Push the Docker image to a container registry.

    A container registry is a centralized place to store and manage Docker images. You can use a public registry like Docker Hub or a private registry like Google Container Registry.

    Use the docker push command to push the Docker image to the registry.

     docker push trainwithshubham/django-todo:latest
    

    This command pushes the Docker image to the "savitashelar1799" container registry with the tag "latest".

  6. Creating Pod:

    In Kubernetes, a Pod is the smallest deployable unit that can run a container. A Pod can contain one or more containers that share the same network namespace and can communicate with each other using localhost.

    To create a Pod in Kubernetes, you can define a Pod YAML file. The YAML file defines the desired state of the Pod, including its metadata, the container image to use, and any configuration options.

    Here's an example of a simple Pod YAML file:

     #filename to be save:pod.yml
     apiVersion: v1
     kind: Pod
     metadata:
       name: django-todo
       namespace: django-todo-ns
     spec:
       containers:
       - name: django-todo
         image: trainwithshubham/django-todo:latest
         ports:
         - containerPort: 8000
    

    This YAML file creates a Pod with the name "django-todo" and a single container named "django-todo".

    Use the kubectl apply command to apply the Pod YAML file and start running the containerized application.

     kubectl apply -f pod.yaml
    

    Check image is created and running on the worker node (Optional) :

     sudo su
     # use your token created on master node and append '--v=5' next to it.
     kubeadm join 172.31.89.51:6443 --token s6wpw7.6qv1883o4owun9sz --discovery-token-ca-cert-hash sha256:5a4cc95bb193e6f14def99980a54b3f168f8717e76c80e90a94a4a3a09c5529d --v=5
     docker ps
     #use your container ID and port giveni pod.yml
     docker exec -it 2c7c739a9e91 bash
     curl -L http://127.0.0.1:8000
    
  7. Deploy the application on Kubernetes.

    Use Kubernetes commands to deploy the application in a containerized environment. Create a Kubernetes deployment YAML file that specifies the desired state of your application, including the number of replicas, container image, and other configuration options.

    Here is an example of a simple deployment YAML file:

     #filename to be save:deployment.yml
     apiVersion: apps/v1
    
     kind: Deployment
     metadata:
       name: django-todo-deployment
       namespace: django-todo-ns
       labels:
         app: django-todo
     spec:
       replicas: 3
       selector:
         matchLabels:
           app: django-todo
       template:
         metadata:
           labels:
             app: django-todo
         spec:
           containers:
           - name: django-todo
             image: trainwithshubham/django-todo:latest
             ports:
             - containerPort: 8000
    

    This YAML file creates a deployment called "django-todo" with three replicas. The deployment uses the container image "trainwithshubham/django-todo:latest" and exposes port 8000.

    Use the kubectl apply command to apply the deployment YAML file and start running the containerized application.

     kubectl apply -f deployment.yaml
    

    Checking created replicas (Optional):

     kubectl get pods -n=django-todo-ns
     #Below shows updated result each 2 sec
     watch kubectl get pods -n=django-todo-ns
     #Below shows result in brief description
     kubectl get pods -o wide -n=django-todo-ns
    
  8. Creating a service for pod(access app from outside)

    In Kubernetes, a Service is an abstraction that defines a logical set of Pods and a policy by which to access them. A Service provides a stable IP address and DNS name for a set of Pods, allowing other Pods and external clients to access them without needing to know their individual IP addresses.

    Here's an example of a Service YAML file:

     #filename to be save:service.yml
     apiVersion: v1
     kind: Service
     metadata:
       name: django-todo-service
       namespace: django-todo-ns
     spec:
       type: NodePort
       selector:
         app: django-todo
       ports:
           # By default and for convenience, the `targetPort` is set to the same value as the `port` field.
         - port: 80
           targetPort: 8000
           # Optional field
           # By default and for convenience, the Kubernetes control plane will allocate a port from a range (default: 30000-32767)
           nodePort: 30007
    

    This YAML file creates a Service with the name "django-todo-service" that routes traffic to Pods with the label "app=django-todo". The Service exposes port 30007, which is the nodePort that the Pods are listening on.

    Use the kubectl apply command to apply the Service YAML file and start running the containerized application.

     kubectl apply -f service.yaml
    

    Checking created service(Optional):

     kubectl get service -n django-todo-ns
     #use your namespace after -n
    
  9. Adding Inbound rule on the security group of the Worker node.

    Checking application execution on browser.

    URL : <Public IP of instance>:<nodePort>

    Ex: http://52.207.92.145:30007/todos/

    Get a detailed description of application deployment:

     kubectl describe deployment.apps/django-todo-deployment -n django-todo-ns
    
  10. Creating a secret.yml file for passing confidential data(Optional)

    In Kubernetes (k8s), secrets are used to store sensitive information such as passwords, API keys, and other confidential data that should not be stored in plaintext in a container image or in a pod's configuration.

    The below file is for passing MySql credentials:

    #filename to be save:secret.yml
    apiVersion: v1
    kind: Secret
    metadata:
      name: mysql-secret
      namespac: mysql-db
    type: Opaque
    data:
      password: dHJhaW53aXRoc2h1YmhhbQ==
    #password encoded using echo 'mydbpassword' | base64
    
    #creating mysql-db namespace
    kubectl create namespace mysql-db
    #applying secret.yml file
    kubectl apply -f secret.yml
    

Creating configMap.yml file

In Kubernetes (k8s), a ConfigMap is used to store configuration data such as environment variables, command-line arguments, and configuration files for applications running inside pods.

kind: ConfigMap
apiVersion: v1
metadata:
  name: mysql-config
  labels:
    app: mysql
  namespace: mysql-db
data:
  MYSQL_DB: "todo-db"
kubectl apply -f configMap.yml

By following the above steps we can easily deploy our application on Kubernetes.

K8S containerization provides a powerful way to package and deploy your applications in a consistent and scalable way. By using Kubernetes containerization, you can ensure that your application runs consistently across different environments, and you can scale your application to handle increasing levels of traffic.


Thank you, Readers, for giving your precious time to read my first-ever blog. I am open to your valuable suggestions to upskill myself. Glad to share my learnings of #DevOps in the #trainwithshubham community during the #90daysofdevops challenge. Your appreciation will motivate me to learn and share upcoming learnings.

0
Subscribe to my newsletter

Read articles from Savita Shelar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Savita Shelar
Savita Shelar