Skip to content

Instantly share code, notes, and snippets.

@Ivanshamir
Created August 10, 2024 21:31
Show Gist options
  • Select an option

  • Save Ivanshamir/593cc32c7d748a5922fe17bb3b67c5a0 to your computer and use it in GitHub Desktop.

Select an option

Save Ivanshamir/593cc32c7d748a5922fe17bb3b67c5a0 to your computer and use it in GitHub Desktop.
DEPLOY A SIMPLE FLASK APPLICATION IN KUBERNETES
  1. 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)
  1. 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"]
  1. 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
  1. 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
  2. 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
  1. Build and Deploy: make all
  2. check pod is active or not: kubectl get pod -o wide
  3. Cleanup: make clean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment