- Create the Flask REST API
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return jsonify(message="Hello, World!")
@app.route('/hello/<name>')
def hello(name):
return jsonify(message=f"Hello, {name}!")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
- Create a Dockerfile
FROM python:3.9-slim
# Set the working directory in the container
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install the required dependencies
RUN pip install --no-cache-dir flask
# Make port 5000 available to the world outside this container
EXPOSE 5000
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["python", "app.py"]
- Create Kubernetes Deployment and Service YAML
apiVersion: apps/v1
kind: Deployment
metadata:
name: flask-app
spec:
replicas: 2
selector:
matchLabels:
app: flask-app
template:
metadata:
labels:
app: flask-app
spec:
containers:
- name: flask-app
image: ivanshamir/flask-app:latest
ports:
- containerPort: 5000
---
apiVersion: v1
kind: Service
metadata:
name: flask-app-service
spec:
selector:
app: flask-app
ports:
- protocol: TCP
port: 80
targetPort: 5000
type: LoadBalancer
- Before create makefile we will export docker password so that makefile can use the password and push image to dockerhub:
export DOCKER_PASSWORD=your_password_here
- Create a Makefile:
DOCKER_USERNAME ?= ivanshamir
IMAGE_NAME = $(DOCKER_USERNAME)/flask-app
IMAGE_TAG ?= latest
FULL_IMAGE_NAME = $(IMAGE_NAME):$(IMAGE_TAG)
KUBE_NAMESPACE = default
# Targets
all: build push deploy
build:
@echo "Building Docker image..."
docker build -t $(FULL_IMAGE_NAME) .
push: docker-login
@echo "Pushing image to DockerHub..."
docker push $(FULL_IMAGE_NAME)
docker-login:
@echo "Logging into DockerHub..."
@docker login -u $(DOCKER_USERNAME) -p $(DOCKER_PASSWORD)
deploy:
@echo "Deploying to Kubernetes..."
kubectl apply -f deployment.yaml --namespace $(KUBE_NAMESPACE)
clean:
@echo "Cleaning up..."
kubectl delete -f deployment.yaml --namespace $(KUBE_NAMESPACE)
.PHONY: all build push deploy clean docker-login
- Build and Deploy:
make all
- check pod is active or not:
kubectl get pod -o wide
- Cleanup:
make clean