DEV Community

Josef Polar
Josef Polar

Posted on

Getting Started with Kubernetes: Creating a Basic Service

Run an app in a container, then expose it so traffic could actually reach it. Two resources handle this: a Deployment and a Service.

Step 1: Writing the Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: my-app
          image: echo-server:latest
          ports:
            - containerPort: 80
Enter fullscreen mode Exit fullscreen mode

This tells Kubernetes to run 2 copies of echo-server and label them app: my-app. The label part matters — I'll need it in a second.

Step 2: Writing the Service

apiVersion: v1
kind: Service
metadata:
  name: my-app-service
spec:
  selector:
    app: my-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: ClusterIP
Enter fullscreen mode Exit fullscreen mode

The selector matches the label I set in the Deployment. That's how Kubernetes knows which pods to send traffic to. Once I understood that connection, the rest started clicking.

Step 3: Applying both files

kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
Enter fullscreen mode Exit fullscreen mode

Then I checked that everything came up:

kubectl get pods
kubectl get services
Enter fullscreen mode Exit fullscreen mode

Two pods in Running state, and the service listed with a cluster IP. Good sign.

Step 4: Testing it locally

kubectl port-forward service/my-app-service 8080:80
Enter fullscreen mode Exit fullscreen mode

Opened http://localhost:8080 in the browser and got the echo-server return page. It worked.

Top comments (0)