DevOps - Kubernetes Part-3
DevOps - Kubernetes Tutorial - Part 3
Learn Kubernetes with architecture, developer tools, and a real Java API example.
1From Docker to Kubernetes
In Docker Parts 1 and 2, we explored container images, volumes, and Compose. Kubernetes helps maintain the desired state of container workloads across machines. Docker can build images; Kubernetes manages running them in a cluster.
2Cluster Architecture
The control plane manages desired state, while worker nodes run application Pods. This simplified diagram is conceptual; actual cluster layouts vary.
- API server and etcd: The API accepts requests; etcd stores cluster state.
- Scheduler and controllers: The scheduler assigns Pods to suitable nodes; controllers reconcile actual state toward desired state.
- Node and kubelet: A node runs applications; kubelet manages Pods and the container runtime on that node.
3Essential Concepts
- Pod: The smallest deployable unit, containing one or more cooperating containers.
- Deployment: Manages desired Pod replicas and updates. It attempts to replace failed Pods.
- Service: Provides a stable network identity for selected Pods. ClusterIP is available inside the cluster by default.
- Namespace and labels: A namespace organizes resources; labels and selectors connect resources.
- ConfigMap and Secret: ConfigMaps hold non-sensitive configuration. Configure appropriate access control and encryption for Secrets; base64 alone is not protection.
4Developer Tools
- kubectl: Command-line tool for inspecting clusters, applying resources, logs, and debugging.
- Minikube or kind: Local clusters for learning and testing. kind needs a container runtime such as Docker; Minikube prerequisites depend on its driver.
- Helm: Packages and configures related Kubernetes resources as charts. Review chart contents and sources before installing.
- k9s: Terminal UI for inspecting resources and logs. It also uses your Kubernetes context and permissions.
- Metrics Server: When configured, supplies metrics for
kubectl topand resource-based autoscaling; it is not a complete monitoring solution.
5Live Example Prerequisites
The following example runs a real Java HTTP API in two Kubernetes Pods. Use a personal local test cluster only; it has no database or authentication.
kubectland a running local Kubernetes cluster are required. The node needs internet to pull the publiceclipse-temurin:17-jdkimage.- Allow enough CPU and memory for two Pods; pulling the image and starting Java can take time. Host port 8080 must be free.
- Run the checks below first. Continue only on your own local cluster and stop if the namespace or example names already exist.
kubectl config current-context
kubectl get nodes
kubectl get namespace a143mk-k8s-demo
A not-found response to the last command means the namespace can be created. Do not continue on another error, the wrong context, or an existing namespace.
6Java API and Kubernetes YAML
Below is the complete example: Java source in a ConfigMap, a Deployment that runs it, and a Service that reaches the Pods. Save the single YAML as a143mk-k8s-demo.yaml. No separate project or Docker build is required.
Within the cluster, the Service routes traffic to ready Pods matching its selector. In this local port-forward example, kubectl selects one Pod; it does not demonstrate load balancing.
apiVersion: v1
kind: ConfigMap
metadata:
name: a143mk-api-source
data:
HelloApi.java: |
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
public class HelloApi {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", exchange -> {
try (exchange) {
String path = exchange.getRequestURI().getPath();
int status;
String body;
if (!"GET".equals(exchange.getRequestMethod())) {
exchange.getResponseHeaders().set("Allow", "GET");
status = 405;
body = "{\"error\":\"Method not allowed\"}";
} else if ("/api/hello".equals(path)) {
status = 200;
body = "{\"message\":\"Hello from Kubernetes!\"}";
} else if ("/health".equals(path)) {
status = 200;
body = "{\"status\":\"UP\"}";
} else {
status = 404;
body = "{\"error\":\"Not found\"}";
}
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
exchange.getResponseHeaders().set("Access-Control-Allow-Origin", "*");
exchange.getResponseHeaders().set("Cache-Control", "no-store");
exchange.sendResponseHeaders(status, bytes.length);
exchange.getResponseBody().write(bytes);
}
});
server.start();
System.out.println("Java API listening on port 8080");
}
}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: a143mk-api
spec:
replicas: 2
selector:
matchLabels:
app: a143mk-api
template:
metadata:
labels:
app: a143mk-api
spec:
containers:
- name: api
image: eclipse-temurin:17-jdk
command: ["java", "--add-modules", "jdk.httpserver", "/app/HelloApi.java"]
ports:
- containerPort: 8080
resources:
requests:
cpu: 100m
memory: 256Mi
limits:
memory: 512Mi
startupProbe:
httpGet:
path: /health
port: 8080
periodSeconds: 10
failureThreshold: 30
readinessProbe:
httpGet:
path: /health
port: 8080
periodSeconds: 10
livenessProbe:
httpGet:
path: /health
port: 8080
periodSeconds: 10
volumeMounts:
- name: source
mountPath: /app
readOnly: true
volumes:
- name: source
configMap:
name: a143mk-api-source
---
apiVersion: v1
kind: Service
metadata:
name: a143mk-api
spec:
selector:
app: a143mk-api
ports:
- port: 80
targetPort: 8080
type: ClusterIP
The startup probe allows time for slow startup; a failed readiness probe makes the Pod unavailable for normal Service traffic. Repeated liveness failures can cause a container restart.
7Deploy and Test the API
After completing the prerequisite checks, open a terminal where you saved the YAML. Create the namespace, apply the resources, and wait for rollout:
kubectl create namespace a143mk-k8s-demo
kubectl -n a143mk-k8s-demo apply -f a143mk-k8s-demo.yaml
kubectl -n a143mk-k8s-demo rollout status deployment/a143mk-api --timeout=300s
kubectl -n a143mk-k8s-demo get deployment,pods,service
If rollout does not succeed, stop and see troubleshooting below. Once it succeeds, start port forwarding in this terminal and leave it running:
kubectl -n a143mk-k8s-demo port-forward service/a143mk-api 8080:80
In another terminal, call the real API from PowerShell or open http://localhost:8080/api/hello in a browser:
Invoke-RestMethod http://localhost:8080/api/hello
Invoke-RestMethod http://localhost:8080/health
Successful JSON responses are {"message":"Hello from Kubernetes!"} and {"status":"UP"}. Press Ctrl+C in the port-forward terminal to stop it.
8Live Browser Request
This button sends a real GET http://localhost:8080/api/hello request; it is not a simulation. Run the example above and keep port forwarding active first.
The button calls localhost on the computer running the browser. Browser or blog security policies may block local requests; if so, use the PowerShell command above.
9Scaling and Troubleshooting
Inspect status, details, and logs in the demo namespace. Run the scale command only on the demo Deployment:
kubectl -n a143mk-k8s-demo get pods -l app=a143mk-api
kubectl -n a143mk-k8s-demo describe deployment a143mk-api
kubectl -n a143mk-k8s-demo logs deployment/a143mk-api --tail=50
kubectl -n a143mk-k8s-demo scale deployment/a143mk-api --replicas=3
kubectl -n a143mk-k8s-demo rollout status deployment/a143mk-api --timeout=300s
Scaling needs enough node resources. Reapplying the YAML may restore its desired replicas: 2. The Deployment logs command shows one Pod's logs, not all Pods.
- Pending: Inspect events with
kubectl -n a143mk-k8s-demo describe pod POD_NAME; check node resources and scheduling. Replace POD_NAME with your Pod name. - ImagePullBackOff: Check the image name, network, and registry access in Pod events.
- CrashLoopBackOff or not ready: Inspect Pod events, container logs, memory, and probe paths. For previous container logs use
kubectl -n a143mk-k8s-demo logs POD_NAME --previous. - API unreachable: Check rollout, ready Pods, the Service selector, ports, and the running port-forward terminal.
Remove only your demo resources
If you created these three resources and no longer need them, stop port forwarding first, then delete them. The namespace is retained; do not delete other resources.
kubectl -n a143mk-k8s-demo delete deployment/a143mk-api service/a143mk-api configmap/a143mk-api-source
10Production Readiness
- Build and scan a tested application image, use a pinned image digest, and include tests and review in CI.
- Configure least-privilege RBAC, appropriate Secret protection, non-root containers, and network policies for your cluster.
- Design readiness and liveness for the application's behavior. A process-only check does not prove a database is available.
- Choose CPU and memory requests/limits from measurements; plan capacity, logs, metrics, alerts, and rollback.
- For persistent data, choose appropriate storage and test backup and recovery. Ingress or Gateway, TLS, and external access require separate configuration.
11Quick Quiz
12What to Learn Next
Next, explore rolling updates, ConfigMaps and Secrets, persistent storage, Ingress, and building and deploying images through CI/CD pipelines.
Official documentation: Kubernetes concepts and Kubernetes tutorials.
DevOps - Kubernetes Part 4
DevOps - Kubernetes Tutorial - Part 4
Update a Java API and explore configuration, storage, networking, and deployment tools.
1Workload Architecture
Part 3 introduced a Java API, Deployment, and Service. We will use that example to learn updates and configuration. This diagram is a general architecture, not an automatically installed solution.
A ConfigMap and Secret can supply configuration; a PersistentVolumeClaim requests storage. Ingress or Gateway must be configured separately in the cluster.
2Live Example Prerequisites
The real commands require your own local cluster and the a143mk-k8s-demo namespace, a143mk-api Deployment and Service from Part 3. If you removed them, recreate the Part 3 example first.
kubectl config current-context
kubectl -n a143mk-k8s-demo get deployment,service
kubectl -n a143mk-k8s-demo rollout status deployment/a143mk-api --timeout=300s
kubectl -n a143mk-k8s-demo set env deployment/a143mk-api --list
Confirm the context is your local cluster and the resources are your Part 3 demo. Stop if DEMO_RELEASE or APP_GREETING already exists; the exercises use those names. Run commands one at a time and continue only after each succeeds. The environment list may contain sensitive values; do not publish it.
3Rolling Update and Rollback
Changing a Deployment's Pod template starts a new rollout. Kubernetes gradually brings up new Pods and removes old ones; readiness and available capacity affect the result.
Interactive diagram: This browser simulation illustrates stages; it does not change a cluster.
Real local update
After the prerequisite checks, add a non-sensitive environment variable only to your demo Deployment. This creates a new Pod template, but does not change the Java API response or image.
kubectl -n a143mk-k8s-demo set env deployment/a143mk-api DEMO_RELEASE=v2
kubectl -n a143mk-k8s-demo rollout status deployment/a143mk-api --timeout=300s
kubectl -n a143mk-k8s-demo rollout history deployment/a143mk-api
kubectl -n a143mk-k8s-demo get pods -l app=a143mk-api
If an earlier revision is present, inspect it with kubectl -n a143mk-k8s-demo rollout history deployment/a143mk-api --revision=N, replacing N with its revision number. Roll back your demo only if it is the intended previous template. Rollback does not automatically restore external data or ConfigMaps.
kubectl -n a143mk-k8s-demo rollout undo deployment/a143mk-api
kubectl -n a143mk-k8s-demo rollout status deployment/a143mk-api --timeout=300s
kubectl -n a143mk-k8s-demo set env deployment/a143mk-api --list
4Practical ConfigMap
A ConfigMap holds non-sensitive configuration. Here we add a demo variable to the container environment. The Part 3 Java API does not read it, so its JSON response will not change.
First check that the name is unused. Stop if you get an error other than NotFound or the ConfigMap already exists. Then create and attach your ConfigMap:
kubectl -n a143mk-k8s-demo get configmap a143mk-app-config
Only if the result is NotFound, create it; attach it to the Deployment only after creation succeeds:
kubectl -n a143mk-k8s-demo create configmap a143mk-app-config --from-literal=APP_GREETING=Hello
kubectl -n a143mk-k8s-demo set env deployment/a143mk-api --from=configmap/a143mk-app-config
kubectl -n a143mk-k8s-demo rollout status deployment/a143mk-api --timeout=300s
kubectl -n a143mk-k8s-demo exec deployment/a143mk-api -- printenv APP_GREETING
The final command should print Hello. Environment variables are supplied when a container starts; changing the ConfigMap does not automatically change an already running container's environment.
Remove only your demo configuration
If you created the variable and ConfigMap above and have finished the exercise, first remove the variable from the Deployment. Delete your ConfigMap only after the rollout succeeds:
kubectl -n a143mk-k8s-demo set env deployment/a143mk-api APP_GREETING-
kubectl -n a143mk-k8s-demo rollout status deployment/a143mk-api --timeout=300s
Only after the rollout succeeds, delete only the ConfigMap you created:
kubectl -n a143mk-k8s-demo delete configmap a143mk-app-config
5Secrets and Security
Do not put passwords, tokens, or keys in a ConfigMap, Git, image, or blog example. A Kubernetes Secret is a separate resource for sensitive data, but base64 is not encryption.
- Protect access: Configure least-privilege RBAC, encryption at rest in etcd, and appropriate auditing.
- Manage lifecycle: Use your platform's approved secret manager and rotation process; keep secrets out of command history, logs, and screenshots.
- Limit exposure: Give a Secret only to workloads that need it; design applications to handle rotation and errors.
Read more: Kubernetes Secrets.
6Persistent Storage
A container's writable layer is not suitable for persistent data. A PersistentVolumeClaim (PVC) requests storage from the cluster; a suitable StorageClass or existing PersistentVolume is required.
This YAML is illustrative; do not apply it yet. Select the storage class, access mode, capacity, permissions, and backups for your cluster. The Java API does not mount this PVC.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: example-data
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
ReadWriteOnce means read-write mounting on one node, not necessarily one Pod. Deleting a PVC or backing storage can cause data loss; check reclaim policy and backups.7Service and Ingress
The Part 3 ClusterIP Service is normally reachable inside the cluster. Local testing uses kubectl port-forward; external HTTP access needs additional components such as an Ingress controller or Gateway.
This HTTP Ingress YAML is illustrative. It requires an appropriate nginx IngressClass and controller, DNS, and the Part 3 Service in the same namespace. It does not configure TLS or authentication; do not expose it directly to the public.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: example-api
spec:
ingressClassName: nginx
rules:
- host: api.example.test
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: a143mk-api
port:
number: 80
The hostname api.example.test is only a placeholder. Gateway API is another option and also requires a supported controller and configuration.
8Autoscaling and Observability
A Horizontal Pod Autoscaler (HPA) can adjust replicas based on metrics. CPU-based HPA needs resource metrics and CPU requests for relevant containers; node capacity does not automatically increase.
This YAML is for learning; verify Metrics Server, the target Deployment, policy, and capacity before applying it. The Part 3 demo already has a CPU request.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: a143mk-api
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: a143mk-api
minReplicas: 2
maxReplicas: 4
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
The 70% target is average utilization relative to CPU requests, not 70% of a CPU limit. HPA and manual replica changes can affect each other.
- Logs: Inspect application logs and Pod events; keep sensitive data out of logs.
- Metrics: With Metrics Server available, use
kubectl top pods. Complete monitoring needs separate metrics collection and alerts. - Traces and alerts: Observe latency, error rates, and request flow; test alerts for the application's needs.
9Tools and CI/CD Flow
This is a conceptual flow, not a configured pipeline. The Part 3 demo runs source from a ConfigMap; for real CI/CD, first prepare a testable application image and secure registry access.
- kubectl: CLI for inspecting rollouts, logs, and resources.
- Helm or Kustomize: Tools to package or customize Kubernetes configuration; review rendered changes before applying.
- Prometheus and Grafana: Common tools for metrics collection/querying and dashboards, respectively; configure security and alerts separately.
- CI/CD platforms: GitHub Actions, GitLab CI/CD, or Jenkins can automate tests and deployments; restrict cluster credentials.
Documentation: Deployments, Kustomize, and Prometheus.
10Troubleshooting and Checklist
For inspection only, in your Part 3 demo namespace:
kubectl -n a143mk-k8s-demo get deployment,pods,service
kubectl -n a143mk-k8s-demo describe deployment a143mk-api
kubectl -n a143mk-k8s-demo logs deployment/a143mk-api --tail=50
kubectl -n a143mk-k8s-demo rollout history deployment/a143mk-api
- Rollout stalled: Check Pod events, image pulls, available resources, and readiness probes.
- ConfigMap value missing: Check the name, key, and Deployment environment; wait for a new Pod to become ready.
- API call fails: Check ready Pods and the Service. A rollout can remove the Pod selected by port-forward; restart it if needed.
- PVC Pending: Check StorageClass, available PersistentVolumes, access mode, and provisioner events.
11Quick Quiz
12What to Learn Next
Next: package a Java application into an image and learn build, test, scan, and Kubernetes deployment in a secure CI/CD pipeline.