OpenCost — Kubernetes Cost Tracking
OpenCost (CNCF incubating) breaks down your Kubernetes cluster costs by namespace, deployment, pod, and custom labels. See exactly which teams and services are consuming your cloud budget.
Helm Installation
# Add the OpenCost Helm repo helm repo add opencost https://opencost.github.io/opencost-helm-chart helm repo update # Install OpenCost in the opencost namespace helm install opencost opencost/opencost \ --namespace opencost \ --create-namespace \ --set opencost.exporter.cloudProviderApiKey="AIzaSyD-9tSrke72..." \ # GCP only --set opencost.prometheus.internal.enabled=true # For AWS, set the cluster region and node pricing helm install opencost opencost/opencost \ --namespace opencost \ --create-namespace \ --set opencost.exporter.aws.region=us-east-1 \ --set opencost.prometheus.internal.enabled=true # Access the UI (port-forward) kubectl port-forward -n opencost svc/opencost 9090:9090 9003:9003 & open http://localhost:9090
REST API — Query Namespace Costs
# Cost by namespace, last 7 days, accumulated total
curl "http://localhost:9090/model/allocation?window=7d&aggregate=namespace&accumulate=true" \
| jq '.data[0] | to_entries | map({namespace: .key, cost: .value.totalCost}) | sort_by(-.cost)'
# Cost by deployment in a specific namespace
curl "http://localhost:9090/model/allocation?window=30d&aggregate=deployment&accumulate=true&filter=namespace:production" \
| jq '.data[0] | to_entries[] | {deployment: .key, cost: .value.totalCost}'
# Cost by team label (requires pods to have label app.kubernetes.io/team)
curl "http://localhost:9090/model/allocation?window=7d&aggregate=label:team&accumulate=true"
# Daily cost breakdown for a namespace (accumulate=false)
curl "http://localhost:9090/model/allocation?window=14d&aggregate=namespace&accumulate=false&filter=namespace:staging" \
| jq '.data[] | {date: .window.start, cost: .["staging"].totalCost}'
# Assets API — raw node/disk costs
curl "http://localhost:9090/model/assets?window=7d&aggregate=type&accumulate=true" Python Script — Weekly Cost Report
import requests
import json
OPENCOST_URL = "http://localhost:9090"
def get_namespace_costs(window="7d"):
resp = requests.get(f"{OPENCOST_URL}/model/allocation", params={
"window": window,
"aggregate": "namespace",
"accumulate": "true"
})
data = resp.json()["data"][0]
costs = [
{"namespace": k, "cost": round(v["totalCost"], 2), "cpu": round(v["cpuCost"], 2), "memory": round(v["ramCost"], 2)}
for k, v in data.items()
]
return sorted(costs, key=lambda x: x["cost"], reverse=True)
def print_report():
costs = get_namespace_costs("30d")
total = sum(c["cost"] for c in costs)
print(f"\\n=== Kubernetes Cost Report (Last 30 Days) ===")
print(f"Total cluster cost: ${total:.2f}\\n")
print(f"{'Namespace':<30} {'Total':>10} {'CPU':>10} {'Memory':>10}")
print("-" * 65)
for c in costs[:15]:
print(f"{c['namespace']:<30} ${c['cost']:>9.2f} ${c['cpu']:>9.2f} ${c['memory']:>9.2f}")
print_report() OpenCost vs Kubecost Comparison
| Feature | OpenCost (free) | Kubecost Free |
|---|---|---|
| Cost allocation API | ✓ Full REST API | ✓ Full REST API |
| Basic UI | ✓ Minimal dashboard | ✓ Rich dashboard |
| Savings recommendations | ✗ Not included | ✓ Basic rightsizing |
| Multi-cluster | Manual aggregation | ✗ Paid only |
| Metric retention | Prometheus-backed | 15 days free |
| RBAC / SSO | ✗ | ✗ Paid only |
| License | Apache 2.0 | BSL / proprietary |
Frequently Asked Questions
What is OpenCost and how is it different from Kubecost?▼
OpenCost is the open-source, CNCF-incubating project that originated as Kubecost's core cost allocation engine. Kubecost is the commercial product built on top of it. OpenCost provides the core cost allocation logic — breaking down cluster costs by namespace, deployment, pod, and label — and exposes a REST API and basic UI. Kubecost adds a richer UI, multi-cluster support, savings recommendations, RBAC, SSO, and 15-day metric retention in the free tier. For teams that want open-source with no vendor dependency, OpenCost is the right choice. For teams that need the recommendations engine and multi-cluster UI, Kubecost free tier (or commercial) is better.
How does OpenCost calculate the cost of each pod?▼
OpenCost models costs by allocating node costs proportionally to each pod's resource requests (CPU and memory). It queries the cloud provider's pricing API (or a custom on-prem price sheet) to get the hourly cost of each node. Then it divides that cost proportionally: if your pod requests 0.5 of a 2-CPU node, it's allocated 25% of the node's cost. Network and storage costs are also tracked. The key insight is that OpenCost uses requests (not actual utilization) for allocation, which means over-provisioned pods show up as expensive even if idle — a feature, not a bug.
How do I query OpenCost for namespace costs via the API?▼
OpenCost exposes a REST API at /model/allocation on port 9090. The key parameters are: window (time range, e.g., '7d' or 'lastmonth'), aggregate (dimension to group by: namespace, pod, deployment, label:team), and accumulate (true to sum the window, false for daily breakdown). Example: GET http://localhost:9090/model/allocation?window=7d&aggregate=namespace&accumulate=true returns total cost per namespace for the last 7 days. Add &filter=namespace:production to scope to one namespace. The API is the foundation for building custom dashboards in Grafana.
Can OpenCost track costs for on-premises Kubernetes clusters?▼
Yes. For on-prem clusters, OpenCost uses a custom pricing configuration instead of cloud pricing APIs. You define CPU and RAM costs per core/GB-hour in a ConfigMap, and OpenCost uses those rates for allocation. This is useful for bare-metal or private cloud environments where you want to do internal chargeback — showing each team their 'bill' based on resource consumption even if it's not a real cloud bill. Set pricingModel.defaultSpotCPUCoreHours and similar fields in the OpenCost ConfigMap.
Related Products
on GumroadPremium Workflow Pack
Production-grade workflows, architecture guides, and deployment scripts for teams that ship. 10 advanced CI/CD workflows (blue-green, canary, E2E, security), 5 architecture deep-dives, code review checklist, PR process guide, and 5 battle-tested Bash deployment scripts.
Buy on Gumroad →GitHub Actions CI/CD Templates Pack
12 production-ready GitHub Actions workflow templates covering Node.js, Python, Docker, multi-environment deployments, security scanning, and auto-changelog. Copy, paste, ship.
Buy on Gumroad →Developer Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →You Might Also Need
Kubernetes Resource Estimator
Estimate total Kubernetes cluster CPU and memory requirements. Input pods, replicas, and resource requests/limits to get cluster totals, requests vs limits analysis, and a ready-to-use ResourceQuota YAML.
Open free tool →
Kubernetes Resource Calculator
Calculate total CPU and memory requirements for your Kubernetes workloads. Input resource requests and limits per pod, replica count, and get cluster resource usage with cloud cost estimates.
Open free tool →
Kubernetes Resource Calculator
Calculate K8s resource requests and limits. Input CPU cores, memory per pod, replica count. Output cluster resource needs, HPA config, namespace quota YAML.
Open free tool →
More Free Tools
Related Articles
Kubernetes Cost Optimization: A Practical Guide for 2026
Reduce your Kubernetes costs by 40-60% with rightsizing, VPA/HPA, spot instances, namespace quotas, and cost monitoring tools like Kubecost. Real examples included.
FinOps Engineering: A Developer's Guide to Cloud Cost Optimization in 2026
A practical guide to FinOps for engineers: AWS, GCP, and Azure cost tools, Infracost for Terraform, right-sizing, spot instances, reserved capacity, auto-scaling, and the FinOps maturity model. With code examples for CI/CD cost gates.
FinOps for Kubernetes: Cut Cloud Costs by 40% Without Slowing Engineering
Practical FinOps strategies for Kubernetes in 2026. Use Kubecost, KEDA, spot instances, and right-sizing to reduce cloud bills by 40% while maintaining performance.
Pulumi vs Terraform 2026: Which IaC Tool Should You Choose?
A deep comparison of Pulumi and Terraform for infrastructure as code in 2026. Covers syntax, state management, provider ecosystem, team adoption, and when to choose each tool.
Cloud Cost Optimization in 2026: Strategies, Tools, and Real-World Savings
Cut your cloud bill without cutting performance. This practical guide covers FinOps practices, cost allocation, resource optimization, reserved capacity strategies, and the tools that help engineering teams understand and reduce cloud spend.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →