Hi Everyone,
Hope everyone is doing great.
In this blog we will learn how to create small Python REST API and deploy the same to SAP BTP, Kyma Environment using Kubernetes, and Docker containerized.
There are 2 different options so far I have learned.
- Using GitHub Package Registry
- Using Docker
Pre-requisites
- Create SAP BTP Trial/Tier Account
- Enable SAP BTP Kyma Environment
- Git Hub Account /Docker Account – Will be used for container registry.
- Visual Studio (VS) Code Setup or Any IDE of your choice
- Python Setup
- Install & Set up Kubernetes
- Docker Desktop Set up for Mac or Windows
- Docker Hub (Optional)
Step 1: Now let us start creating our python application. Create a new folder, here I am naming it as py-flask-kubernetes and open the same folder in the VS Code and start running docker locally.
Step 2: Now, create Python file app.py with below code.
from flask import Flask, jsonify
import time
PORT = 8080
app = Flask(__name__)
@app.route("/")
def root():
return jsonify({"App Status" : "Running"})
@app.route("/getTime")
def getTime():
seconds = time.time()
local_time = time.localtime(seconds)
return jsonify({"Year" : local_time.tm_year,"Seconds" : seconds, "Local Time" : local_time})
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=PORT)
Step 3: Test the python app locally using python3 app.py
Step 4: Create requirements.txt which holds the information about the dependency libraries, modules, and packages for the project.
flask
Step 5: To containerize the application lets us create Dockerfile from which generates docker image for this application.
FROM python:3.7
RUN mkdir /app
WORKDIR /app
ADD . /app/
RUN pip install -r requirements.txt
CMD ["python", "/app/app.py"]
Step 6: (Consider if you want to publish to GitHub Package Registry) Now lets us create Personal Access Token (PAT) to login to Git Account
Login to Git Hub Account => Go to Settings à Developer Settings => Personal Access Tokens (PAT).
Click on Generate new token.
Provide the token name and check repo and packages access and click on Generate Token below and token will get generated. Copy and save this token so that we will be using this in next steps
Step 7: (Consider if you want to publish to GitHub Package Registry) git login
git config --global user.name <<GitHubUserName>>
git config --global user.email <<GitHubEmailID>>
git config --global user.password <<GitHubAccessToken>>
Step 8: Now let’s create Kubernetes Secret Key in the SAP BTP, Kyma Environment. Make sure you have configured local workspace to BTP Kyma Environment while Kubernetes setup. Here I am going with default namespace
kubectl config set-context --current --namespace=<insert-namespace-name-here>
kubectl config view --minify | grep namespace:
GitHub Registry
kubectl create secret docker-registry py-regcred
--namespace default
--docker-server=ghcr.io
--docker-email=<<GitHubEmailID>>
--docker-username=<<GitHubUserName>>
--docker-password=<<GitHubAccessToken>>
Docker Registry
kubectl create secret docker-registry regcred
--namespace default
--docker-server=docker.io
--docker-email=<<DockerEmailID>>
--docker-username=<<DockerUserName>>
--docker-password=<<DockerPassword>>
On successful creation we can see secret key got created in the BTP Kyma Environment. To check it, open Kyma Dashboard è choose default namespace on the top right => Configuration => Secrets
Step 9: Now will generate the docker image for this app.
GitHub Registry
docker build . --tag ghcr.io/<<GITHubUserID>>/py-flask-kubernetes:latest
docker build . --tag ghcr.io/sainithesh/py-flask-kubernetes:latest
docker run ghcr.io/sainithesh/py-flask-kubernetes:latest
Docker Registry
docker build . --tag docker.io/sainithesh/py-flask-kubernetes:latest
docker run docker.io/sainithesh21/py-flask-kubernetes:latest
Step 10: Publish to Package Registry
GitHub Registry
docker push ghcr.io/sainithesh/py-flask-kubernetes:latest
Docker Registry
docker push docker.io/sainithesh21/py-flask-kubernetes:latest
Step 11: Now we want to deploy this containerized application which is there in the image. Create deployment.yaml with below code.
Here we must use ghcr.io if you deploy image to GitHub or use docker.io and append with image path.
image: ghcr.io/sainithesh/py-flask-kubernetes:latest
Or
image: docker.io/sainithesh/py-flask-kubernetes:latest
Service kind: Act as load balancer
Deployment kind: Act as application
API Rules: which helps in adding rules to the applications like restricting methods (GET, POST, PUT, etc), authentications and other rules.
apiVersion: apps/v1
kind: Deployment
metadata:
name: py-flask-kubernetes
labels:
app: py-flask-kubernetes
spec:
selector:
matchLabels:
app: py-flask-kubernetes
replicas: 1
template:
metadata:
labels:
app: py-flask-kubernetes
spec:
containers:
- name: py-flask-kubernetes
image: ghcr.io/sainithesh/py-flask-kubernetes:latest
imagePullPolicy: Always
ports:
- containerPort: 8080
resources:
limits:
ephemeral-storage: 256M
memory: 256M
cpu: 100m
requests:
ephemeral-storage: 256M
memory: 256M
cpu: 100m
imagePullSecrets:
- name: py-regcred
status: {}
---
apiVersion: v1
kind: Service
metadata:
name: py-flask-kubernetes
spec:
selector:
app: py-flask-kubernetes
ports:
- protocol: "TCP"
port: 8081
targetPort: 8080
---
apiVersion: gateway.kyma-project.io/v1alpha1
kind: APIRule
metadata:
name: py-flask-kubernetes
spec:
gateway: kyma-gateway.kyma-system.svc.cluster.local
service:
name: py-flask-kubernetes
port: 8081
host: py-flask-kubernetes
rules:
- path: /.*
methods: ["GET"]
accessStrategies:
- handler: noop
config: {}
Step 12: Deploy to Kyma Environment
kubectl apply -n default -f deployment.yaml
Step 13: Manual Deployment to Kyma Environment
Deployment
Workloads => Deployments => Create Deployment
Go to YAML tab and copy the deployment Code and click on Create.
Once Deployment object is created, we can see it running as below
Service: To create service for an application
Discovery and Network => Services => Create Service
API Rules:
Step 14: Pods, here we can see multiple instances for the same application which depends on the replica attribute value which is part of Service. Multiple instances here helps application to keep running even if one of the instance breaks down or crash because of any reason like heavy traffic or others.
Step 15: Service Details, here we can see the application url.
Step 16: (Consider if you published image to GitHub Registry Package) Let us push the code to the Git repo so that we can update image using GitHub Actions whenever we push new build to Git repo.
Let us create workflow file (here docker_build_and_push.yml) in the Git repo under github/workflows folder. We need to collaborate package and repo to make workflow enabled.
name: Build and Push Docker Imag
on: [push]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build_and_push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v3
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
with:
buildkitd-flags: --debug
- name: Login to GitHub Container Registry
uses: docker/login-action@v2
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.PKG_SECRET }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v4
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Build the py-flask-kubernetes Docker image
uses: docker/build-push-action@v3.0.0
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
Step 17: We can see all the GitHub Actions under Action Tab. On successful completion of workflow on every push to Git repo, new docker image will get updated.
Hope this blog helps you. Feel free to add comment and suggestions.
Git Repo: https://github.com/SaiNithesh/py-flask-kubernetes/