
Containerizing Python web applications encapsulates the application structure and dependencies into a single package to ensure consistent and reproducible deployments across different environments. Deploying containerized Python web applications is a fundamental approach to modern software development that involves scaling and automation when deploying to platforms such as Kubernetes.
You can build Python applications using different development frameworks. Each platform may require a slightly different approach to containerize and ship the application image. Popular Python frameworks include:
This article explains how to containerize Python web applications for deployment in production environments such as Kubernetes clusters.
Before you begin:
Deploy a Vultr Kubernetes Engine (VKE) cluster to use as the production deployment platform.
Create a Vultr Container Registry to store the Python application image.
Deploy a One-Click Docker instance to use as the management workstation.
Access the workstation using SSH as a non-root user with sudo privileges.
Install and configure Kubectl to access the cluster.
Install the Helm CLI tool to install additional cluster applications.
To create a consistent Python web application image that you can use with different frameworks such as Flask or Django, structure your code to separate the frontend HTTP server interface logic from the main application logic. Follow the steps below to create a basic Python application using app.py as the main application file while using a server.py file to include the basic HTTP server logic.
Install the Python virtual environment and the PIP package manager.
Create a new project directory to store the application files.
Switch to the directory.
Create a new Python virtual environment to separate the application dependencies from other system packages.
Activate the virtual environment.
Create the main application file app.py using a text editor such as Nano.
Add the following code to the file.
Save and close the file.
The above code creates a basic Python web application that displays a Hello, World! prompt. Within the application:
hello_world function prints the Hello, World! string when called.if __name__ == "__main__":: Checks if the script runs as the main program. This ensures that certain code elements run when the script starts with the main thread. If the script is the main program, it calls the hello_world function.Create a new server.py file to set up a basic HTTP application using the Python http.server and socketserver modules.
Add the following code to the file.
Save and close the file.
The above application code responds to incoming GET requests with a Hello, World! prompt. Within the code:
HelloWorldHandler: Defines a custom handler class that inherits the SimpleHTTPRequestHandler HTTP module function to handle GET requests.start_server: Creates a TCPServer instance running on the host port 8000. In addition, it captures KeyboardInterrupt exceptions Ctrl + C interrupts to gracefully shut down the server.(if __name__ == "__main__":): Starts the HTTP server in a separate thread using the Thread(target=start_server) function. Then, it imports and calls a hello_world function from the app module. server_thread.join() waits for the server thread to complete before closing the connection.Start the Python application as a background task in your server session.
Output:
Send a GET request to the host port 8000 to verify access to the application.
Output:
When the above GET request fails, verify that no conflicting applications run on the defined host port 8000.
View the background application Job ID.
Output:
Stop the application by Job ID. For example 1.
Deactivate your virtual environment.
Create a new Dockerfile Dockerfile to set up your Python application container image.
Add the following contents to the file.
Save and close the file.
The above Dockerfile configuration defines the Python container directory and run-time structure. Within the configuration:
FROM python:3.8-slim: Uses the official Python 3.8 image as the base image to run the container.WORKDIR /app: Sets the working directory to /app inside the container.COPY . /app: Copies data from your project directory to the container.CMD ["python3", "./server.py"]: Runs the server.py script when the container starts.Build the Docker image with all directory files.
View the local Docker images to verify that the application is available.
Output:
To store and use the Python application image on a platform such as Kubernetes, push the image to the Vultr Container Registry to ship it to your target environments as described in the steps below.
Log in to your Vultr Container Registry. Replace pythonregistry, vcr-user, vcr-password with your actual registry details.
Tag the local Docker image with your target Vultr Container Registry repository.
View the list of available Docker images and verify that the registry image is available.
Output:
Push your Python application image to the Vultr Container Registry.
Output:
Start a new Docker container using your registry container image to test access to the application.
View the list of running Docker containers to verify that your application container is available.
Output:
Send a new GET request to the host port 8000 to verify access to the application container.
Output:
To securely deploy your containerized Python application in a production environment such as a Kubernetes cluster, set up access to your Vultr Container Registry and install the application image as a new Deployment resource. When deployed, your application container listens for incoming connections on port 8000 as defined in the container configuration. Follow the steps below to deploy and use your Python application image in a Vultr Kubernetes Engine (VKE) cluster.
Access your Vultr Container Registry control panel.
Navigate to the Docker/Kubernetes tab, and click Generate Kubernetes YAML to generate a new registry Secret resource configuration.
Create a new Secret resource file secret.yaml.
Add your generated Vultr Container Registry YAML configuration to the file similar to the one below:
Save and close the file.
Deploy the Secret to your cluster.
View the cluster resources to verify that your registry credentials are ready to use.
Output:
Create a new Deployment resource file deployment.yaml to describe how to run your application in a pod.
Add the following configurations to the file. Replace sjc.vultrcr.com/pythonregistry/python-app:latest with your actual Vultr Container Registry repository.
Save and close the file.
Apply the deployment to your cluster.
View the cluster deployments to verify that the new resource is available.
Output:
View the cluster pods to verify all pods associated with your deployment.
Output:
To Expose your Python application for external access using your Vultr Kubernetes Engine (VKE) cluster, install an Ingress controller to map your application service to a domain name. The controller securely routes all application requests from your domain name to the backend Python application service. Follow the steps below to expose the application in your VKE cluster.
Add the NGINX ingress repository to your Helm sources.
Update the Helm repository index.
Install the NGINX Ingress Controller to your cluster using Helm.
Wait for at least 3 minutes for the Nginx Ingress Controller to install all necessary CRDs. Then, view the controller services to verify the assigned load balancer IP address.
Output:
Keep note of the Ingress controller EXTERNAL-IP value to externally access your cluster services.
Set Up a new domain A record pointing to the Ingress controller public IP address. For example, app.example.com.
Create a new Python Service resource file service.yaml
Add the following contents to the file.
Save and close the file.
The above Service configuration forwards all network requests on the HTTP port 80 to your Python application port 8000.
Apply the Service to your cluster.
Create a new Ingress resource file ingress.yaml to expose the Python application service.
Add the following contents to the file. Replace app.example.com with your actual domain,
Save and close the file.
The above Ingress configuration forwards all root requests from app.example.com to your Python application service on port 80.
Apply the Ingress resource to your cluster.
View the cluster Ingress objects and verify that the new resource is available.
Output:
Access your domain using a web browser such as Firefox to test access to the application.
You have containerized a Python application and stored it in a Vultr Container Registry repository for deployment in a VKE cluster. Shipping Python web applications as container images enables the efficient management and upgrade of application components for deployment in multiple environments.
0 Comments
Be the first to comment and share your perspective with the community.