GitHub EN PT

K8s by Example: Hello World

Let’s deploy a web server and access it. This is the Kubernetes equivalent of “Hello World” - create a Deployment, expose it with a Service, and make a request.

hello.yaml

A Deployment manages replicas of your application. It ensures the desired number of pods are always running.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello

Run 2 replicas. The selector must match the pod template labels - this is how the Deployment knows which pods it owns.

spec:
  replicas: 2
  selector:
    matchLabels:
      app: hello

The template defines the pods. Each pod runs an nginx container that serves a default welcome page on port 80.

  template:
    metadata:
      labels:
        app: hello
    spec:
      containers:
        - name: web
          image: nginx:alpine
          ports:
            - containerPort: 80

A Service provides a stable endpoint to access the pods. ClusterIP is the default type - accessible only within the cluster.

---
apiVersion: v1
kind: Service
metadata:
  name: hello

The selector routes traffic to pods with matching labels. Port 80 on the Service forwards to port 80 on the pods.

spec:
  selector:
    app: hello
  ports:
    - port: 80
      targetPort: 80
terminal

Apply the manifest. Kubernetes creates the Deployment, which creates a ReplicaSet, which creates the pods.

$ kubectl apply -f hello.yaml
deployment.apps/hello created
service/hello created
terminal

Check the pods are running. The random suffix in the name comes from the ReplicaSet.

$ kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
hello-5d7b9d8c7f-k2x9m   1/1     Running   0          10s
hello-5d7b9d8c7f-p8z4n   1/1     Running   0          10s
terminal

The Service gets a cluster IP. This IP is stable - pods can come and go, but the Service IP stays the same.

$ kubectl get svc hello
NAME    TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
hello   ClusterIP   10.96.45.123   <none>        80/TCP    15s
terminal

Test the Service from inside the cluster. We spin up a temporary pod with curl and hit the Service by name. DNS resolves hello to the Service IP.

$ kubectl run curl --image=curlimages/curl --rm -it -- curl -s hello
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
...
terminal

To access from your machine, use port-forward. This tunnels localhost:8080 to the Service. Open http://localhost:8080 in your browser.

$ kubectl port-forward svc/hello 8080:80
Forwarding from 127.0.0.1:8080 -> 80

# In another terminal:
$ curl localhost:8080
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
...
terminal

Clean up by deleting everything defined in the manifest.

$ kubectl delete -f hello.yaml
deployment.apps "hello" deleted
service "hello" deleted

Index | Use arrow keys to navigate