1. Home
  2. Blog
  3. DevOps

DevOps

Kubernetes Tutorial for Beginners: Deploy, Scale and Update Your First App

Learn what Kubernetes actually does, then use it on your own laptop. Start a local cluster, deploy an app, expose it, scale it, roll out a new version and diagnose the errors beginners hit most.

11 min read
Kubernetes tutorial for beginners: deploy, scale and update your first app

Key takeaways

  • Kubernetes runs containers across many machines and keeps them in the state you describe.
  • You declare what you want in YAML, and controllers work continuously to make it true.
  • Learn three objects first: Pods run containers, Deployments manage Pods and Services give them a stable address.
  • kubectl describe and kubectl logs solve most beginner problems.

Kubernetes has a reputation for being hard, largely because tutorials throw twenty new terms at you before anything runs. This Kubernetes tutorial for beginners takes the opposite approach. You learn the handful of ideas that matter, and then you use each one on a real cluster running on your own laptop.

You should already know what a container is. If not, work through our Docker Compose tutorial first. Commands here are the standard ones from the Kubernetes documentation, but output and flags can vary a little between versions.

What is Kubernetes?

Kubernetes, often written K8s, is an open-source platform for running containers across a group of machines. Google originally developed it, and the Cloud Native Computing Foundation now maintains it.

Its central idea is desired state. You do not tell it “start three containers”. You declare “there should always be three copies of this app”. Kubernetes compares that statement with reality and keeps fixing any difference. If a container crashes or a machine dies, it starts a replacement without anyone being paged.

Do you need Kubernetes?

Often, you do not, at least not yet. Be honest about this before you take on the complexity.

Your situation Reasonable choice
Local development, or one small server Docker Compose
A small app and no operations team A managed platform, such as a PaaS or serverless containers
Many services, several teams, multiple machines Kubernetes, usually a managed offering
You need rolling updates, autoscaling and failover at scale Kubernetes

Learning it is still valuable, because it has become a common skill in DevOps and platform roles. In production, most teams use a managed service such as Amazon EKS, Google GKE or Azure AKS, rather than running the control plane themselves.

How Kubernetes works

A cluster has two parts: a control plane that makes decisions, and worker nodes that run your applications.

Component Where Job
kube-apiserver Control plane The front door; every command goes through it
etcd Control plane Key-value store holding the cluster’s state
kube-scheduler Control plane Chooses a node for each new Pod
kube-controller-manager Control plane Runs loops that match reality to desired state
kubelet Each node Starts Pods and reports on their health
kube-proxy Each node Handles network rules for Services
Container runtime Each node Actually runs containers, such as containerd

When you apply a manifest, kubectl sends it to the API server, which stores it in etcd. Controllers notice the change and create Pods, the scheduler assigns them to nodes, and each node’s kubelet starts the containers. You do not need to memorise this today, but it explains why things happen in the order they do.

Core objects you need first

  • Pod: the smallest deployable unit, made up of one or more containers that share a network address. Pods are disposable, and you rarely create them directly.
  • Deployment: describes how many copies of a Pod to run and which image to use. It handles replacement and updates.
  • Service: gives a changing group of Pods one stable name and address, and balances traffic across them.
  • Namespace: a way to divide one cluster into logical groups, such as by team or environment.
  • ConfigMap and Secret: hold configuration and sensitive values outside the image.

Start a local cluster

You need three things: a container runtime such as Docker Desktop, kubectl (the command-line client) and minikube (which runs a small cluster on your machine). Follow the official install steps for your operating system, and then run:

minikube start
kubectl get nodes

You should see one node with the status Ready. That single node plays both roles here, which is fine for learning. Alternatives such as kind and k3d work similarly.

Deploy an app

Create a file called deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: nginx
          image: nginx:1.27
          ports:
            - containerPort: 80
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 128Mi

Every manifest has the same four top-level fields: apiVersion, kind, metadata and spec. The part to study is the connection between selector.matchLabels and template.metadata.labels. Labels are how Kubernetes objects find each other, so a mismatch here is an error. The resource requests tell the scheduler how much room the Pod needs.

Apply it and watch what happens:

kubectl apply -f deployment.yaml
kubectl get deployments
kubectl get pods -l app=web

Two Pods should reach Running status within a minute or so, after the image has downloaded.

Expose it with a Service

Each Pod has its own IP address, but that address disappears along with the Pod. A Service solves this. Create service.yaml:

apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  type: NodePort
  selector:
    app: web
  ports:
    - port: 80
      targetPort: 80
kubectl apply -f service.yaml
minikube service web --url

The second command prints a local URL. Open it, and you should see the nginx welcome page. Here are the main Service types:

Type Reachable from Typical use
ClusterIP Inside the cluster only (default) Internal services and databases
NodePort A port on each node Local testing
LoadBalancer A cloud load balancer Public apps on a managed cluster

For websites with many routes and domains, you would also add an Ingress or the newer Gateway API, which routes HTTP traffic to Services.

Scale and watch it self-heal

This is where Kubernetes starts to feel useful. Scale up with a single command:

kubectl scale deployment web --replicas=4
kubectl get pods -l app=web

Now test self-healing. Delete a Pod, using a name from the list above:

kubectl delete pod <pod-name>
kubectl get pods -l app=web

A replacement appears almost at once, because the Deployment still wants four copies. Note that the scale command changed the live cluster but not your file. Update replicas in the YAML as well, or your next apply will set it back to two.

Tip: Treat your YAML files as the source of truth and keep them in Git. Quick commands are fine for experiments, but files make every change reviewable and repeatable.

Roll out an update

Change the image to nginx:1.28 in deployment.yaml and apply it again. Kubernetes performs a rolling update, starting new Pods and removing old ones gradually, so the app stays available.

kubectl apply -f deployment.yaml
kubectl rollout status deployment/web
kubectl rollout history deployment/web

If the new version is bad, go back to the previous one:

kubectl rollout undo deployment/web

Teams usually automate this from a pipeline, where a merge builds an image and updates the manifest. Our guides on what is CI/CD and GitHub Actions explain how that works.

Configuration and health probes

Keep settings outside your image, so one image can run in every environment. Add environment variables from a ConfigMap, and health checks that tell Kubernetes when a container is working:

        - name: nginx
          image: nginx:1.28
          envFrom:
            - configMapRef:
                name: web-config
          readinessProbe:
            httpGet:
              path: /
              port: 80
          livenessProbe:
            httpGet:
              path: /
              port: 80

A failing readiness probe stops traffic reaching the Pod until it recovers. A failing liveness probe restarts the container. Create the ConfigMap with kubectl create configmap web-config --from-literal=LOG_LEVEL=info before you apply this change. For passwords, use a Secret, and remember that Secrets are only base64-encoded by default, so restrict access to them and consider encryption at rest.

Debug common errors

Almost every beginner problem starts with the same three commands:

kubectl get pods
kubectl describe pod <pod-name>
kubectl logs <pod-name> --previous

Read the Events section at the bottom of the describe output, because it usually names the cause. Use --previous to see logs from a container that has already crashed.

Status Usual cause What to check
ImagePullBackOff Wrong image name or tag, or no registry access The image line and pull secrets
CrashLoopBackOff The app keeps exiting after it starts kubectl logs --previous
Pending No node has enough resources Events and resource requests
OOMKilled The container exceeded its memory limit The limit and the app’s memory use
Service gives no response Selector does not match Pod labels kubectl get endpoints

When you finish, clean up with kubectl delete -f deployment.yaml -f service.yaml, and then minikube stop.

Final thoughts

You have now used the core Kubernetes loop: declare a state, apply it and let the cluster keep it true. Everything else builds on that. As your next step, deploy one of your own containers, add a real readiness endpoint, and connect it to a database through a ClusterIP Service. After that, look at Helm, Ingress and autoscaling.

Frequently asked questions

Is Kubernetes hard to learn?

The basics are manageable. Pods, Deployments and Services are enough for a first app. Running production clusters is much harder, which is why many teams use managed services.

Should I learn Docker before Kubernetes?

Yes. Kubernetes runs containers, so you should understand images, ports and environment variables first. A few hours with Docker is enough to get started.

What is the difference between a Pod and a container?

A container runs one process and its dependencies. A Pod wraps one or more containers that share networking and can share storage, and it is what Kubernetes schedules.

What is the difference between Kubernetes and Docker Compose?

Compose runs a group of containers, typically on one host, and is ideal for development. Kubernetes runs them across many machines, with scheduling, scaling and self-healing.

Can I learn Kubernetes for free?

Yes. Kubernetes, minikube, kind and kubectl are all free, and they run on an ordinary laptop. You pay only if you later use a cloud-managed cluster.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →