Deploying an Internal AI Solution: Ollama + OpenWebUI

In short
  • Beyond the marketing hype, generative AI brings a real (r)evolution.
  • Ollama runs LLMs locally; OpenWebUI provides a web interface similar to ChatGPT.
  • Example of complete deployment under Kubernetes.
  • Kubernetes supports GPUs: this is the subject of a dedicated article.

Introduction

As part of an article aimed at explaining how to add a worker node to an existing Kubernetes cluster, I integrated a physical node into my own cluster (which I describe the deployment of in a dedicated cookbook).

My goal was to be able to test the combination of Ollama and OpenWebUI to obtain a local AI assistant solution.

AI: Between Hype and Opportunity

As of writing this tutorial, AI is still in full hype mode, with a proliferation of announcements, products, and daily revolutions surrounding the topic.

The term AI is slapped on everything. You can't escape the marketing bullshit, where all sorts of applications are suddenly topped with the two letters that have become almost mandatory in any self-respecting IT PowerPoint presentation.

I couldn't escape the trend. I must admit that once the marketing fairy dust has settled, there is a real (r)evolution behind the emergence of ChatGPT, with an ultra-interesting ecosystem to explore.

It didn't take long for open source to establish quality projects led by excellent developers who are motivated to offer an alternative to the market giants.

One of the concerns often raised in companies regarding the implementation of AI, and particularly ChatGPT-like solutions (MS Copilot, Google Gemini...), is the use of data and the associated risks: data leaks, misuse, dependencies on third parties... This has caused great distrust in some companies, and a general alert in many cybersecurity departments, with CISOs and risk managers often panicking at the idea of all their employees sharing all the company's secrets with OpenAI & Co.'s servers.

There was exactly the same reaction with the arrival of the internet in the professional world. I myself experienced the famous single PC for the entire department, and only that machine was allowed to browse the internet with explicit management authorization (which doesn't make me feel any younger...).

Except that reality is what it is: imagining working tomorrow without AI... means taking a bigger risk of missing a great opportunity to accelerate your business than of seeing your company go under because of a generative AI mishap.

I'm not saying that the danger doesn't exist, but almost no one today considers the risk they take when doing a search on Google, posting a snippet of code on Stack Overflow, or using community forums... there are also many opportunities to unintentionally disclose sensitive information.

It is better to educate than to prohibit (although it all depends on the professional environment).

Like any tool, AI needs to be used correctly, knowing what you are doing (and especially in what context you are using it).

Now, if the use of online services poses too great a risk for your business and you do not want to depend on a third-party provider to utilize AI, there are completely on-premise solutions that can run on local servers.

Ollama: The AI Model Store

Ollama is one of those fantastic tools that today offers access to multiple generative AI models in a very simple and efficient way.

Founded in 2023 by Jeffrey Morgan and Michael Chiang, the application is completely open source and has achieved great success.

Its principle is to provide access to many neural network models made public, such as llama from Facebook or Mistral from our French startup.

Each model can be retrieved very easily with a CLI (Command Line Interface) using basic terms (like "pull"). It is even possible to get customized versions of the models, with more or fewer parameters, depending on whether you favor execution speed or answer accuracy.

Access to the models is inspired by application stores, where you can browse hundreds of models through a simple website, with a description of their usage, ranging from general-purpose AIs to specialized AIs.

Once the model is downloaded, it runs locally, and its performance depends on the resources you have allocated to the platform where Ollama is installed.

No online connection is required to use the model, and all information exchanged remains local to your Ollama instance.

Ollama does not provide a GUI (Graphical User Interface), which is where the second application comes in: OpenWebUI.

OpenWebUI: An Interface to Rule Them All

Created at the end of 2023 by Timothy Jaeryang Baek and also released as open source, this project perfectly complements Ollama and integrates seamlessly with it. It provides a graphical interface heavily inspired by ChatGPT, making it very easy to interact with the different models you have downloaded via Ollama.

An Example of Deployment Under Kubernetes

After this long introduction, it's time to take action. Of course, I decided to deploy this winning combination on Kubernetes and utilize my physical node.

As I have done before, notably in the section about deploying an application under K8S, I will start by describing my Kubernetes objects and how they fit together.

To isolate my deployment, I will dedicate a namespace that follows my naming convention: prd-mygpt-lan. (This is created using the command kubectl create ns prd-mygptlan-lan).

Here is a schematic overview of what will be executed on the cluster.

Target diagram for installation under Kubernetes

Click the image to enlarge.

I won't go into detail for each object used. If you want more information about how K8S works and how to deploy an application on this platform, feel free to browse my cookbook on the subject and learn about the different definitions associated with the Pod, the Deployment, the Service, and Kubernetes itself.

In the case we are interested in today, which is setting up Ollama and OpenWebUI, the particularity lies in the persistent volume for Ollama and its choice of node to run on.

Indeed, each AI model you want to test must be downloaded locally. Depending on the chosen model, the disk space occupied can be significant. We will also need performance, and it is not certain that a PersistentVolume (pv) based on a network filesystem such as NFS (Network File System) or SMB (Server Message Block) is sufficient in this regard.

As I don't have a professional storage infrastructure, I will have to rely on the local storage of my physical K8S worker.

This uses an NVME SSD, so I should be able to offer a level of performance that I hope is sufficient.

However, I will create a dependency between my application and the server, since the data will be hosted locally. If my container were to restart on another node in the cluster, it would start with blank data.

Given the educational nature of the project, this isn't a problem, but in a production environment, it is clear that using local storage for a node should only be considered in certain cases where data loss is not or is minimally problematic (such as an application cache).

Otherwise, the rest of the configuration remains based on standard logic. Only the OpenWebUI part needs to be associated with an Ingress, because it is the part that must be accessible from outside the cluster. The Ollama part only needs to be accessible internally within the cluster by OpenWebUI (via the K8S Service associated with Ollama).

Prerequisites for Using Local Storage

This is a somewhat particular configuration. Despite using local storage on a node, it is preferable to declare a StorageClass (sc). This class only serves to maintain a standard logic for the use of persistent storage spaces (StorageClass(sc) / PersistentVolumeClaim(pvc) / PersistentVolume(pv)).

This sc does not rely on any CSI (Container Storage Interface).

Its creation is done through the following yaml file: 02-sc-local-storage.yml

      
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: sc-local-storage
provisioner: kubernetes.io/no-provisioner  # Indique qu'il n'y a pas de provisionnement dynamique
volumeBindingMode: WaitForFirstConsumer
       
Kubernetes cluster

Click the image to enlarge.

I apply the yaml using the command kubectl apply -f .\02-sc-local-storage.yml

Next, on my physical node, I will create a local folder dedicated to hosting the data for this volume.

In my case, the choice is completely arbitrary. For simplicity, I use the root directory /home, which, in the context of my installation of Rocky Linux (on which I deployed the K8S worker), has the largest partition.

Of course, you can choose what works best for you.

mkdir -p ~/kubernetes/localpv/prd-mygpt-lan/pv-ollama-default
Creating the local path for the persistent volume (PV)

Click the image to enlarge.

Deployment of Ollama

Now that the prerequisites for persistent storage for Ollama are covered, I can move on to the PersistentVolume (pv) itself via the yaml file 01-pv-ollama-default.yml.

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-ollama-default
  labels:
    environment: prd
    network: lan
    application: mygpt
    tier: ollama
spec:
  capacity:
    storage: 250Gi 
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: sc-local-storage
  local:
    path: /home/bvivi57/kubernetes/localpv/prd-mygpt-lan/pv-ollama-default
  nodeAffinity:
    required:
      nodeSelectorTerms:
        - matchExpressions:
            - key: kubernetes.io/hostname
              operator: In
              values:
                - prdk8snod001

              

I refer to my "fictitious" sc and point to the folder that I just created on my physical node.

We can verify that the volume is ready without it being mapped yet, as no pvc refers to it.

kubectl get pv
Checking the PV

Click the image to enlarge.

Now it's time to create the pvc using the YAML file 02-pvc-ollama-default.yml.

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pvc-ollama-default
  namespace: prd-mygpt-lan
  labels:
    environment: prd
    network: lan
    application: mygpt
    tier: ollama
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: sc-local-storage
  resources:
    requests:
      storage: 250Gi
    

Its content references the previous pv.

I apply it with kubectl apply -f .\02-pvc-ollama-default.yml.

We can check its status using the command kubectl describe pvc pvc-ollama-default -n prd-mygpt-lan.

Checking the persistent volume claim (PVC)

Click the image to enlarge.

Since no resource is using it and no Pod refers to it, Kubernetes does not attempt to provision it, and therefore does not map it to the volume created previously.

This will change with the deployment of the pod via the file 03-deploy-ollama-default.yml.

  
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: deploy-ollama-default
  namespace: prd-mygpt-lan
  labels:
    environment: prd
    network: lan
    application: mygpt
    tier: ollama
spec:
  replicas: 1
  selector:
    matchLabels:
      environment: prd
      network: lan
      application: mygpt
      tier: ollama
  template:
    metadata:
      labels:
        environment: prd
        network: lan
        application: mygpt
        tier: ollama
    spec:
    nodeSelector:
      type: physical  # Associe le pod aux nœuds ayant le label `type=physical` 
        tolerations:
          - key: "node-role.kubernetes.io/worker-lan-physical"
            operator: "Exists"
              effect: "NoSchedule" 
      containers:
        - name: ollama
          image: ollama/ollama:0.4.0-rc6
          ports:
            - containerPort: 11434
          volumeMounts:
            - name: pv-ollama-default
              mountPath: "/root"
      volumes:
        - name: pv-ollama-default
          persistentVolumeClaim:
            claimName: pvc-ollama-default
          

The Deployment object allows us to apply placement constraints for the pod. Indeed, I want to exclusively use my node prdk8snod001 (my physical worker) because the persistent data is attached to a local location on the server. I also want to take advantage of all available resources to make the use of Ollama as efficient as possible by dedicating this worker to its use.

To do this, I use the nodeselector concept in the Pod template to utilize the label type: physical, which only exists for my physical worker, as well as toleration for the taint node-role.kubernetes.io/worker-lan-physical. (More details here).

Feel free to adapt this section to your own use.

We also find the pvc, which will allow me to map the pv in /root at the level of the container within the pod.

Regarding the rest, there's nothing special to detail. Once again, feel free to refer to the section of my cookbook that discusses deploying an application under K8S to learn more.

We apply the deployment using the command: kubectl apply -f .\03-deploy-ollama-default.yml.

After this step, we can observe with the command kubectl get pvc -n prd-mygpt-lan that this time the pvc is being used, and the pv is in a mounted state.

We can verify that the Pod is properly deployed using the command kubectl get pod -n prd-mygpt-lan -o wide.

Checking the pod

Click the image to enlarge.

We note that the Pod is running on prdk8snod001, which is exactly what we intended.

Furthermore, if we enter the context of the container using the command:

kubectl exec -it deploy-ollama-default-56855dc9dd-vqj7d -n prd-mygpt-lan bash (the pod name needs to be adapted)

and we attempt to create a file in /root (a simple touch toto), we can see that this file is indeed located in /home/bvivi57/kubernetes/localpv/prd-mygpt-lan/pv-ollama-default directly at the OS level of the node.

Creating a test file in the PV

Click the image to enlarge.

Checking the file in the folder on the node

Click the image to enlarge.

Therefore, we are using a persistent volume attached to a local storage space on the server where the Pod is running.

Since we're already in the context of the Ollama container, let's take advantage of this to download some AI models.

As I explained earlier in the article, you just need to choose the model of your choice from the marketplace, retrieve the associated pull command, and run it using the Ollama binary.

Searching for the model

Click the image to enlarge.

Example of a model entry

Click the image to enlarge.

For example, if I want to download the llama3.2 model, I just need to type:.

ollama pull llama3.2
Retrieving the model

Click the image to enlarge.

After a few minutes, the model is downloaded and can be used internally within my network via Ollama.

You can try with other models:

Retrieving another model

Click the image to enlarge.

Now we can exit the container to continue deploying the Kubernetes objects.

Next, we use the file 04-svc-ollama-default.yml to declare the service that will make the Ollama instance accessible within the K8S cluster.

 
---
kind: Service
apiVersion: v1
metadata:
  name: svc-ollama-default
  namespace: prd-mygpt-lan
  labels:
    environment: prd
    network: lan
    application: mygpt
    tier: ollama
spec:
  ports:
    - name: ollama
      port: 11434
      protocol: TCP
      targetPort: 11434
  selector:
    environment: prd
    network: lan
    application: mygpt
    tier: ollama
    

There are no particular aspects to note here; we just need to ensure that the selection labels are correctly defined so that the Service matches the Pod once the command >kubectl apply -f .\04-svc-ollama-default.yml is executed.

Deploying the service

Click the image to enlarge.

We don't need any other objects for Ollama; we can now move on to OpenWebUI.

Deployment of OpenWebUI

This tool also requires persistent storage, but this time without specific performance requirements. Therefore, we can use a persistent volume based on the CSI NFS. For those who are interested, I explain how everything works in this article.

I start by defining the persistent volume in the file 06-pv-openwebui-default.yml.

 
---
apiVersion: v1
kind: PersistentVolume
metadata:
  annotations:
    pv.kubernetes.io/provisioned-by: nfs.csi.k8s.io
  name: pv-openwebui-default
  labels:
      environment: prd
      network: lan
      application: mygpt
      tier: openwebui
spec:
  capacity:
    storage: 30Gi
  accessModes:
    - ReadWriteMany
  persistentVolumeReclaimPolicy: Retain
  csi:
    driver: nfs.csi.k8s.io
    volumeHandle: /Volume1/nfsshare/kub.coolcorp.priv/namespaces/prd-mygpt-lan/openwebui
    volumeAttributes:
      server: 192.168.10.152
      share: /Volume1/nfsshare/kub.coolcorp.priv/namespaces/prd-mygpt-lan/openwebui
    

This will access my NAS via the NFS path specified.

I apply the file using the command kubectl apply -f .\06-pv-openwebui-default.yml.

Creating the PV

Click the image to enlarge.

Next, I use the persistent volume claim and the file 07-pvc-openwebui-default.yml:

 
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pvc-openwebui-default
  namespace: prd-mygpt-lan
  labels:
      environment: prd
      network: lan
      application: mygpt
      tier: openwebui
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 30Gi
  volumeName: pv-openwebui-default
  storageClassName: ""

There's nothing special to say here, and I apply it using the command kubectl apply -f .\07-pvc-openwebui-default.yml

Creating the PVC

Click the image to enlarge.

We can now move on to the Deployment via the file 08-deploy-openwebui-default.yml:

 
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: deploy-openwebui-default
  namespace: prd-mygpt-lan
  labels:
    environment: prd
    network: lan
    application: mygpt
    tier: openwebui
spec:
  replicas: 1
  selector:
    matchLabels:
      environment: prd
      network: lan
      application: mygpt
      tier: openwebui
  template:
    metadata:
      labels:
        environment: prd
        network: lan
        application: mygpt
        tier: openwebui
    spec:
      containers:
        - name: open-webui
          image: ghcr.io/open-webui/open-webui:main
          ports:
            - containerPort: 8080
          volumeMounts:
            - name: pv-openwebui-default
              mountPath: "/app/backend/data"
              env: 
                - name: OLLAMA_BASE_URL 
                  value: "http://svc-ollama-default:11434"     
      volumes:
        - name: pv-openwebui-default
          persistentVolumeClaim:
            claimName: pvc-openwebui-default
          

I use the persistent volume claim to map the persistent volume to /app/backend/data within the container.

It is also necessary to set the OLLAMA_BASE_URL variable so that OpenWebUI can communicate with Ollama. In this case, we provide the name of the K8S Service attached to the Ollama Pod that we created just before (specifying the container's exposed port: 11434).

As a reminder, name resolution is handled inside a Kubernetes cluster: through the service name, OpenWebUI can resolve the associated IP and talk to Ollama inside the cluster.

You only need to type the command kubectl apply -f .\08-deploy-openwebui-default.yml to run OpenWebUI.

Deploying OpenWebUI

Click the image to enlarge.

You can verify that the pod has started with the command kubectl get pod -n prd-mygpt-lan -o wide.

Checking the pods

Click the image to enlarge.

Please note that for OpenWebUI, no specific execution constraints were given for the pod. I don't have a requirement for the application to run on a particular node, as is the case with Ollama. Therefore, I leave the choice of pod placement to the orchestrator.

Next comes the service associated with OpenWebUI, using the file 08-svc-openwebui-default.yml:

 
---
kind: Service
apiVersion: v1
metadata:
  name: svc-openwebui-default
  namespace: prd-mygpt-lan
  labels:
    environment: prd
    network: lan
    application: mygpt
    tier: openwebui
spec:
  ports:
    - name: openwebui
      port: 8080
      protocol: TCP
      targetPort: 8080
  selector:
    environment: prd
    network: lan
    application: mygpt
    tier: openwebui
  

There are no particular issues to report either. We are working on port 8080 and using the correct labels so that the Service redirects to the OpenWebUI Pod.

Applying the service

Click the image to enlarge.

Now, we need to publish the URL for OpenWebUI.

To do this, we need a certificate. I won't go into detail about the logic of obtaining a certificate. This depends on your architectures and systems. For those who are interested, I have written an article about deploying and using cert-manager, a tool that allows you to automate the acquisition of certificates within a k8s cluster. You will find the main principles regarding certificates there.

In this specific case, I cannot use cert-manager because I do not want to expose my application on the web and therefore open the URL to request the ACME protocol with Let's Encrypt (more explanations here).

I will use a manual solution. I create a private key and a CSR file using OpenSSL via this command in my WSL instance:

openssl req -new -nodes -sha256 -keyout mygpt.coolcorp.priv.key -out mygpt.coolcorp.priv.csr -newkey rsa:4096 -subj "/C=FR/ST=Ile-de-France/L=Paris/O=COOLCORP/OU=Infrastructure/CN=mygpt.coolcorp.priv" -reqexts SAN -config <(printf "[req]\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[SAN]\nsubjectAltName=DNS:mygpt.coolcorp.priv").

Then, I submit my CSR (Certificate Signing Request) to my internal PKI (Public Key Infrastructure), which in this case is a Windows PKI, and run the command certreq -attrib "CertificateTemplate:TPL-SRV-WEB-DEFAULT" -submit .\mygpt.coolcorp.priv.csr to retrieve a certificate (TPL-SRV-WEB-DEFAULT is the certificate template I use internally to handle all web publishing needs).

Retrieving the certificate

Click the image to enlarge.

Once again, this logic is specific to my infrastructure.

Regardless of what mechanism you use for creating certificates, the important thing is to have a private key and the associated certificate in the end.

With these two files, mygpt.coolcorp.priv.cer and mygpt.coolcorp.priv.key in my case, we can create a secret that will contain these two elements.

To do this, we use the following command:

kubectl create secret generic secret-certificate-mygpt --from-file=tls.crt=mygpt.coolcorp.priv.cer --from-file=tls.key=mygpt.coolcorp.priv.key --namespace prd-mygpt-lan
Creating the secret for the certificate

Click the image to enlarge.

In this way, the secret secret-certificate-mygpt can be used to refer to the key and the certificate.

This is the secret that I will reference in my 09-ing-openwebui-default.yml file:

 
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ing-openwebui-default
  namespace: prd-mygpt-lan
  labels:
    environment: prd
    network: lan
    application: mygpt
    tier: openwebui
  annotations:
    traefik.ingress.kubernetes.io/router.entrypoints: web,websecure
    ingressClassName: traefik-lan
    traefik.ingress.kubernetes.io/router.tls: "true"
spec:
  ingressClassName: traefik-lan
  tls:
  - hosts:
    - mygpt.coolcorp.priv
    secretName: secret-certificate-mygpt
  rules:
  - host: mygpt.coolcorp.priv
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: svc-openwebui-default
            port:
              number: 8080
            

This will allow me to create the Ingress responsible for redirecting external requests made to the URL mygpt.coolcorp.priv.

My Traefik instance on the LAN will manage this Ingress. For more details on how an Ingress controller works and how to deploy Traefik, you can consult this article.

All that remains is to set up the Ingress using the command kubectl apply -f .\09-ing-openwebui-default.yml.

For those who wish to do so, you can retrieve all the YAML files used for this demonstration here

Tests

Everything is now ready. You just need to create a DNS alias that points mygpt.coolcorp.priv to my haproxy instance, which is used upstream of the cluster (see this section of the cookbook), to access the OpenWebUI home page.

We have a valid certificate.

The first step is to create an account.

Creating the account

Click the image to enlarge.

Creating the account

Click the image to enlarge.

Then you can start using the product. In the top left corner, you can select the AI model you want to use. You will find all the models that you have downloaded via Ollama here.

Choosing the model

Click the image to enlarge.

For everything else, it's very similar to ChatGPT, where you can interact with the model through a "chatbot"-like interface.

Example

Click the image to enlarge.

Conclusion

The combination of Ollama and OpenWebUI is impressive because it simplifies the deployment and use of AI within an infrastructure.

The ability to switch between different LLM (Large Language Model) models is extremely interesting.

You can compare the models with each other and rely on the one that seems most relevant depending on your needs. For example, you can keep a model specialized in code writing, such as Starcoder, to help with development, and switch back to a more general-purpose AI like llama3.2 for other tasks.

You can easily update the models and do many other things that I haven't even thought of yet as I write these lines.

In less than a year, the open source community has managed to put increasingly robust and easy-to-use tools in the hands of everyone, capitalizing on the LLM explosion.

However, be aware that even though access to AI is simplified and it becomes possible to have your own "ChatGPT-like" solution internally, this does not eliminate the need for hardware resources.

For your information, my physical node, although a bit old, but based on a 4-core CPU (8 threads) and 32 GB of RAM, is doing its best when Ollama answers my questions.

Resource consumption during requests

Click the image to enlarge.

I experience a latency of about 1 second per character. If you are considering using this in production, you will need to plan for ways to make the entire system run smoothly. Note that Ollama supports GPUs; in fact, it's recommended... but not integrated or basic GPUs.

Apparently, NVIDIA cards are better supported, even though AMD cards are also compatible. This requires revisiting the Ollama installation and passing the right arguments to the pod, probably with additional dependencies. I would love to test this, but I don't have the necessary hardware.

Once again, Kubernetes has perfectly adapted to creating the application and running the associated pods. This article has also allowed me to highlight K8S's ability to dedicate nodes for certain uses and to mix its configurations.

Be aware that K8S also supports GPUs. Recent versions of Kubernetes have brought a lot in this area, and many projects are underway at this level. I am still new to this topic, but if I can find sufficient financial resources, I will try to invest in compatible hardware (and for those who would like to support me, it's here).

Don't hesitate to experiment with the winning Ollama/OpenWebUI duo, whether under Kubernetes or through a more direct installation; there is plenty to build with these two tools... and a way to go from marketing bullshit to real-world results!