This is the multi-page printable view of this section. Click here to print.
Stateless Applications
- 1: Deploy a Release Using a Canary Deployment
- 2: Exposing an External IP Address to Access an Application in a Cluster
- 3: Example: Deploying PHP Guestbook application with Redis
1 - Deploy a Release Using a Canary Deployment
This tutorial walks you through deploying a canary release in Kubernetes. A canary deployment allows you to safely test a new application version with a small portion of production traffic before rolling it out completely. This approach helps minimize risk and enables rapid feedback from real users.
For an overview of canary deployments, see Canary deployments in the Managing Workloads concept page.
Objectives
- Deploy a stable version of an application
- Deploy a canary version alongside the stable version
- Route traffic to both versions using a Service
- Monitor the canary deployment
- Complete the rollout by scaling the canary and removing the stable version
Before you begin
You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:
Understanding canary deployments
A canary deployment is a strategy where you deploy a new version of your application alongside the existing version. The new version (canary) receives a small percentage of traffic, allowing you to:
- Test the new version with real production traffic
- Monitor for errors, performance issues, or unexpected behavior
- Roll back quickly if issues are detected
- Gradually increase traffic to the new version if it performs well
In this tutorial, you'll use the track label to differentiate between the stable and canary releases. The stable release uses track: stable, and the canary release uses track: canary. Both deployments share common labels (app.kubernetes.io/name: rollout-demo) that allow the Service to route traffic to both sets of Pods.
You'll deploy the stable version with 3 replicas and the canary version with 1 replica. Since both versions share the same Service selector (app.kubernetes.io/name: rollout-demo), Kubernetes will load-balance traffic across all 4 pods. With this ratio, approximately 25% of traffic goes to the canary and 75% to the stable version.
Deploying the stable version
First, deploy the stable version of your application:
apiVersion: apps/v1
kind: Deployment
metadata:
name: rollout-demo-stable
labels:
app.kubernetes.io/name: rollout-demo
track: stable
spec:
replicas: 3
selector:
matchLabels:
app.kubernetes.io/name: rollout-demo
track: stable
template:
metadata:
labels:
app.kubernetes.io/name: rollout-demo
track: stable
spec:
containers:
- name: rollout-demo
image: gcr.io/google-samples/hello-app:1.0
ports:
- containerPort: 8080
env:
- name: VERSION
value: "v1"
Apply the stable Deployment:
kubectl apply -f https://k8s.io/examples/application/canary/app-v1-deployment.yaml
Verify that the Deployment was created and the Pods are running:
kubectl get deployments -l app.kubernetes.io/name=rollout-demo
The output is similar to:
NAME READY UP-TO-DATE AVAILABLE AGE
rollout-demo-stable 3/3 3 3 10s
Check the Pods:
kubectl get pods -l app.kubernetes.io/name=rollout-demo
The output is similar to:
NAME READY STATUS RESTARTS AGE
rollout-demo-stable-7d4b9b8c5d-abc12 1/1 Running 0 15s
rollout-demo-stable-7d4b9b8c5d-def34 1/1 Running 0 15s
rollout-demo-stable-7d4b9b8c5d-ghi56 1/1 Running 0 15s
Creating a service
Create a Service to expose your application. The Service selector uses the common label (app.kubernetes.io/name: rollout-demo) and omits the track label, which allows it to route traffic to both the stable and canary Pods:
apiVersion: v1
kind: Service
metadata:
name: rollout-demo-service
labels:
app.kubernetes.io/name: rollout-demo
spec:
type: ClusterIP
selector:
app.kubernetes.io/name: rollout-demo
ports:
- protocol: TCP
port: 80
targetPort: 8080
Apply the Service:
kubectl apply -f https://k8s.io/examples/application/canary/app-service.yaml
Verify the Service was created:
kubectl get service rollout-demo-service
The output is similar to:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
rollout-demo-service ClusterIP 10.96.123.45 <none> 80/TCP 5s
Test the Service by creating a temporary Pod and making a request:
kubectl run curl-test --image=curlimages/curl:latest --rm -it --restart=Never -- curl http://rollout-demo-service
You should see responses from the stable Pods. Run this command multiple times to see different Pod hostnames, but all responses should show version v1.
At this point, your application is in a steady state. In a real-world scenario, you would typically pause here and operate the stable version until you have a new version to deploy. The next steps demonstrate how to introduce a canary version.
Deploying the canary version
To create a canary Deployment, you can copy the stable Deployment manifest and make a few changes:
- Change the
metadata.name(for example, torollout-demo-canary) - Change the
tracklabel fromstabletocanaryin bothmetadata.labelsandspec.selector.matchLabels/spec.template.metadata.labels - Set a lower number of replicas (for example, 1)
- Update the container image to the new version
Now deploy the canary version alongside the stable version:
apiVersion: apps/v1
kind: Deployment
metadata:
name: rollout-demo-canary
labels:
app.kubernetes.io/name: rollout-demo
track: canary
spec:
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: rollout-demo
track: canary
template:
metadata:
labels:
app.kubernetes.io/name: rollout-demo
track: canary
spec:
containers:
- name: rollout-demo
image: gcr.io/google-samples/hello-app:2.0
ports:
- containerPort: 8080
env:
- name: VERSION
value: "v2"
Apply the canary Deployment:
kubectl apply -f https://k8s.io/examples/application/canary/app-v2-deployment.yaml
Verify both Deployments are running:
kubectl get deployments -l app.kubernetes.io/name=rollout-demo
The output is similar to:
NAME READY UP-TO-DATE AVAILABLE AGE
rollout-demo-stable 3/3 3 3 2m
rollout-demo-canary 1/1 1 1 10s
Check all Pods:
kubectl get pods -l app.kubernetes.io/name=rollout-demo -o wide
The output is similar to:
NAME READY STATUS RESTARTS AGE IP NODE
rollout-demo-stable-7d4b9b8c5d-abc12 1/1 Running 0 2m 10.244.1.5 node1
rollout-demo-stable-7d4b9b8c5d-def34 1/1 Running 0 2m 10.244.1.6 node1
rollout-demo-stable-7d4b9b8c5d-ghi56 1/1 Running 0 2m 10.244.2.7 node2
rollout-demo-canary-8e5c0d9f6a-xyz78 1/1 Running 0 15s 10.244.2.8 node2
Notice that you now have 4 Pods total: 3 stable Pods and 1 canary Pod.
Testing traffic distribution
Since both Deployments use the same Service selector (app.kubernetes.io/name: rollout-demo), the Service routes traffic to all Pods. With 3 stable Pods and 1 canary Pod, approximately 25% of requests go to the canary.
Test the Service multiple times to see traffic distribution:
kubectl run curl-test --image=curlimages/curl:latest --rm -it --restart=Never -- \
sh -c 'for i in $(seq 1 10); do curl -s http://rollout-demo-service; echo; done'
You should see responses from both stable and canary versions. The ratio may vary, but you should see some canary responses mixed with stable responses.
Check the Service EndpointSlices to verify both versions are receiving traffic:
kubectl get endpointslices -l kubernetes.io/service-name=rollout-demo-service
The output is similar to (one EndpointSlice per address family; the ENDPOINTS column is truncated by default):
NAME ADDRESSTYPE PORTS ENDPOINTS AGE
rollout-demo-service-abc12 IPv4 8080 10.244.1.5,10.244.1.6,10.244.2.7 + 1 more... 3m
To see all endpoint addresses, use -o yaml.
Monitoring the canary deployment
Monitor your canary deployment for errors, performance issues, or unexpected behavior:
Check Pod logs for the canary:
kubectl logs -l app.kubernetes.io/name=rollout-demo,track=canary --tail=50
Monitor Pod status:
kubectl get pods -l app.kubernetes.io/name=rollout-demo -w
Press Ctrl+C to stop watching.
Check resource usage:
kubectl top pods -l app.kubernetes.io/name=rollout-demo
Note:
Thekubectl top command requires the metrics-server to be installed in your cluster. If it's not available, you can monitor using other methods like Prometheus or cloud provider monitoring tools.Adjusting traffic distribution
If the canary is performing well, you can gradually increase traffic to it by scaling it up:
Scale the canary to 2 replicas (now 40% of traffic):
kubectl scale deployment/rollout-demo-canary --replicas=2
Verify the new Pod is running:
kubectl get pods -l app.kubernetes.io/name=rollout-demo
Continue monitoring. If everything looks good, you can scale the canary further and scale down the stable version.
Completing the rollout
If your monitoring instead uncovered issues with the canary, skip ahead to Rolling back a canary deployment.
Once you're confident that the canary is stable and performing well, complete the rollout:
Scale the canary to the desired number of replicas (e.g., 3):
kubectl scale deployment/rollout-demo-canary --replicas=3
Scale down the stable version to 0:
kubectl scale deployment/rollout-demo-stable --replicas=0
Verify all traffic is going to the canary:
kubectl get pods -l app.kubernetes.io/name=rollout-demo
The output should show only canary Pods:
NAME READY STATUS RESTARTS AGE
rollout-demo-canary-8e5c0d9f6a-xyz78 1/1 Running 0 5m
rollout-demo-canary-8e5c0d9f6a-abc12 1/1 Running 0 2m
rollout-demo-canary-8e5c0d9f6a-def34 1/1 Running 0 2m
Test the Service to confirm all responses are from the canary:
kubectl run curl-test --image=curlimages/curl:latest --rm -it --restart=Never -- curl http://rollout-demo-service
All responses should now show version v2.
To complete the rollout with a single Deployment, first scale the stable Deployment back up so you do not lose capacity if the new image fails to pull. Then update the image and the VERSION environment variable to match the new version, wait for the rollout to complete, and remove the canary Deployment:
kubectl scale deployment/rollout-demo-stable --replicas=3
kubectl set image deployment/rollout-demo-stable rollout-demo=gcr.io/google-samples/hello-app:2.0
kubectl set env deployment/rollout-demo-stable VERSION=v2
kubectl rollout status deployment/rollout-demo-stable
kubectl delete deployment rollout-demo-canary
Rolling back a canary deployment
If you detect issues with the canary version, you can quickly roll back:
Scale down the canary deployment:
kubectl scale deployment/rollout-demo-canary --replicas=0
Scaling to zero preserves the canary Deployment so you can inspect its configuration while you investigate. Once you've finished, delete it with kubectl delete deployment rollout-demo-canary.
Scale the stable version back up if needed:
kubectl scale deployment/rollout-demo-stable --replicas=3
Investigate the issues with the canary before attempting another canary deployment.
Splitting traffic using HTTPRoute (optional)
If you're using the Gateway API, you can use HTTPRoute to have more precise control over traffic splitting between the stable and canary versions. This approach allows you to specify exact percentages for traffic distribution rather than relying on replica counts.
First, create separate Services for the stable and canary versions. This approach is also useful for debugging, even if you are not using Gateway API. By having separate Services, you can directly test or monitor each version independently.
apiVersion: v1
kind: Service
metadata:
name: rollout-demo-stable-service
spec:
selector:
app.kubernetes.io/name: rollout-demo
track: stable
ports:
- protocol: TCP
port: 80
targetPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: rollout-demo-canary-service
spec:
selector:
app.kubernetes.io/name: rollout-demo
track: canary
ports:
- protocol: TCP
port: 80
targetPort: 8080
Then create an HTTPRoute that splits traffic between the two Services:
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: rollout-demo-route
spec:
parentRefs:
- name: example-gateway
hostnames:
- "rollout-demo.example.com"
rules:
- backendRefs:
- name: rollout-demo-stable-service
port: 80
weight: 90
- name: rollout-demo-canary-service
port: 80
weight: 10
This configuration routes 90% of traffic to the stable Service and 10% to the canary Service, regardless of the number of replicas.
You can also use header-based routing to send specific traffic to the canary:
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: rollout-demo-route
spec:
parentRefs:
- name: example-gateway
hostnames:
- "rollout-demo.example.com"
rules:
# Rule 1: Route traffic with canary header to canary service
- matches:
- headers:
- type: Exact
name: env
value: canary
backendRefs:
- name: rollout-demo-canary-service
port: 80
# Rule 2: Split remaining traffic 90/10
- backendRefs:
- name: rollout-demo-stable-service
port: 80
weight: 90
- name: rollout-demo-canary-service
port: 80
weight: 10
This configuration sends all traffic with the env: canary header to the canary Service, while other traffic is split 90/10 between stable and canary.
Note:
The Gateway API requires a Gateway controller to be installed in your cluster. See the Gateway API documentation for installation instructions and supported implementations.Automating canary rollouts
In production environments, canary rollouts are typically managed by controllers or CI/CD systems that automate traffic shifting, monitoring, and promotion or rollback. Tools such as Flux, Argo Rollouts, GitLab, and many others can handle progressive delivery, analysis, and rollback for you. This reduces manual steps and helps ensure safe, repeatable deployments. For more information, see the documentation for your chosen deployment tool or controller.
Cleaning up
Delete the resources created in this tutorial:
kubectl delete deployment rollout-demo-stable rollout-demo-canary
kubectl delete service rollout-demo-service
If you created separate Services for HTTPRoute, delete those as well:
kubectl delete service rollout-demo-stable-service rollout-demo-canary-service
kubectl delete httproute rollout-demo-route
What's next
- Learn more about canary deployments in the Managing Workloads concept page.
- Read about Deployments and how they manage your application lifecycle.
- Read about Services and how they enable service discovery and load balancing.
- Explore the Gateway API for advanced traffic management capabilities.
- Consider using Horizontal Pod Autoscaling to automatically adjust replica counts based on metrics.
2 - Exposing an External IP Address to Access an Application in a Cluster
This page shows how to create a Kubernetes Service object that exposes an external IP address.
Before you begin
- Install kubectl.
- Use a cloud provider like Google Kubernetes Engine or Amazon Web Services to create a Kubernetes cluster. This tutorial creates an external load balancer, which requires a cloud provider.
- Configure
kubectlto communicate with your Kubernetes API server. For instructions, see the documentation for your cloud provider.
Objectives
- Run five instances of a Hello World application.
- Create a Service object that exposes an external IP address.
- Use the Service object to access the running application.
Creating a service for an application running in five pods
-
Run a Hello World application in your cluster:
apiVersion: apps/v1 kind: Deployment metadata: labels: app.kubernetes.io/name: load-balancer-example name: hello-world spec: replicas: 5 selector: matchLabels: app.kubernetes.io/name: load-balancer-example template: metadata: labels: app.kubernetes.io/name: load-balancer-example spec: containers: - image: gcr.io/google-samples/hello-app:2.0 name: hello-world ports: - containerPort: 8080kubectl apply -f https://k8s.io/examples/service/load-balancer-example.yamlThe preceding command creates a Deployment and an associated ReplicaSet. The ReplicaSet has five Pods each of which runs the Hello World application.
-
Display information about the Deployment:
kubectl get deployments hello-world kubectl describe deployments hello-world -
Display information about your ReplicaSet objects:
kubectl get replicasets kubectl describe replicasets -
Create a Service object that exposes the deployment:
kubectl expose deployment hello-world --type=LoadBalancer --name=my-service -
Display information about the Service:
kubectl get services my-serviceThe output is similar to:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE my-service LoadBalancer 10.3.245.137 104.198.205.71 8080/TCP 54sNote:
Thetype=LoadBalancerservice is backed by external cloud providers, which is not covered in this example. Please refer to settingtype: LoadBalancerfor your Service for the details.Note:
If the external IP address is shown as <pending>, wait for a minute and enter the same command again. -
Display detailed information about the Service:
kubectl describe services my-serviceThe output is similar to:
Name: my-service Namespace: default Labels: app.kubernetes.io/name=load-balancer-example Annotations: <none> Selector: app.kubernetes.io/name=load-balancer-example Type: LoadBalancer IP: 10.3.245.137 LoadBalancer Ingress: 104.198.205.71 Port: <unset> 8080/TCP NodePort: <unset> 32377/TCP Endpoints: 10.0.0.6:8080,10.0.1.6:8080,10.0.1.7:8080 + 2 more... Session Affinity: None Events: <none>Make a note of the external IP address (
LoadBalancer Ingress) exposed by your service. In this example, the external IP address is 104.198.205.71. Also note the value ofPortandNodePort. In this example, thePortis 8080 and theNodePortis 32377. -
In the preceding output, you can see that the service has several endpoints: 10.0.0.6:8080,10.0.1.6:8080,10.0.1.7:8080 + 2 more. These are internal addresses of the pods that are running the Hello World application. To verify these are pod addresses, enter this command:
kubectl get pods --output=wideThe output is similar to:
NAME ... IP NODE hello-world-2895499144-1jaz9 ... 10.0.1.6 gke-cluster-1-default-pool-e0b8d269-1afc hello-world-2895499144-2e5uh ... 10.0.1.8 gke-cluster-1-default-pool-e0b8d269-1afc hello-world-2895499144-9m4h1 ... 10.0.0.6 gke-cluster-1-default-pool-e0b8d269-5v7a hello-world-2895499144-o4z13 ... 10.0.1.7 gke-cluster-1-default-pool-e0b8d269-1afc hello-world-2895499144-segjf ... 10.0.2.5 gke-cluster-1-default-pool-e0b8d269-cpuc -
Use the external IP address (
LoadBalancer Ingress) to access the Hello World application:curl http://<external-ip>:<port>where
<external-ip>is the external IP address (LoadBalancer Ingress) of your Service, and<port>is the value ofPortin your Service description. If you are using minikube, typingminikube service my-servicewill automatically open the Hello World application in a browser.The response to a successful request is a hello message:
Hello, world! Version: 2.0.0 Hostname: 0bd46b45f32f
Cleaning up
To delete the Service, enter this command:
kubectl delete services my-service
To delete the Deployment, the ReplicaSet, and the Pods that are running the Hello World application, enter this command:
kubectl delete deployment hello-world
What's next
Learn more about connecting applications with services. Try Deploy a Canary Release to learn how to safely test new application versions in production.
3 - Example: Deploying PHP Guestbook application with Redis
This tutorial shows you how to build and deploy a simple (not production ready), multi-tier web application using Kubernetes and Docker. This example consists of the following components:
- A single-instance Redis to store guestbook entries
- Multiple web frontend instances
Objectives
- Start up a Redis leader.
- Start up two Redis followers.
- Start up the guestbook frontend.
- Expose and view the Frontend Service.
- Clean up.
Before you begin
You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:
Your Kubernetes server must be at or later than version v1.14.To check the version, enter kubectl version.
Start up the Redis Database
The guestbook application uses Redis to store its data.
Creating the Redis Deployment
The manifest file, included below, specifies a Deployment controller that runs a single replica Redis Pod.
# SOURCE: https://cloud.google.com/kubernetes-engine/docs/tutorials/guestbook
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis-leader
labels:
app: redis
role: leader
tier: backend
spec:
replicas: 1
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
role: leader
tier: backend
spec:
containers:
- name: leader
image: "registry.k8s.io/redis@sha256:cb111d1bd870a6a471385a4a69ad17469d326e9dd91e0e455350cacf36e1b3ee"
resources:
requests:
cpu: 100m
memory: 100Mi
ports:
- containerPort: 6379-
Launch a terminal window in the directory you downloaded the manifest files.
-
Apply the Redis Deployment from the
redis-leader-deployment.yamlfile:kubectl apply -f https://k8s.io/examples/application/guestbook/redis-leader-deployment.yaml -
Query the list of Pods to verify that the Redis Pod is running:
kubectl get podsThe response should be similar to this:
NAME READY STATUS RESTARTS AGE redis-leader-fb76b4755-xjr2n 1/1 Running 0 13s -
Run the following command to view the logs from the Redis leader Pod:
kubectl logs -f deployment/redis-leader
Creating the Redis leader Service
The guestbook application needs to communicate to the Redis to write its data. You need to apply a Service to proxy the traffic to the Redis Pod. A Service defines a policy to access the Pods.
# SOURCE: https://cloud.google.com/kubernetes-engine/docs/tutorials/guestbook
apiVersion: v1
kind: Service
metadata:
name: redis-leader
labels:
app: redis
role: leader
tier: backend
spec:
ports:
- port: 6379
targetPort: 6379
selector:
app: redis
role: leader
tier: backend-
Apply the Redis Service from the following
redis-leader-service.yamlfile:kubectl apply -f https://k8s.io/examples/application/guestbook/redis-leader-service.yaml -
Query the list of Services to verify that the Redis Service is running:
kubectl get serviceThe response should be similar to this:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.0.0.1 <none> 443/TCP 1m redis-leader ClusterIP 10.103.78.24 <none> 6379/TCP 16s
Note:
This manifest file creates a Service namedredis-leader with a set of labels
that match the labels previously defined, so the Service routes network
traffic to the Redis Pod.Set up Redis followers
Although the Redis leader is a single Pod, you can make it highly available and meet traffic demands by adding a few Redis followers, or replicas.
# SOURCE: https://cloud.google.com/kubernetes-engine/docs/tutorials/guestbook
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis-follower
labels:
app: redis
role: follower
tier: backend
spec:
replicas: 2
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
role: follower
tier: backend
spec:
containers:
- name: follower
image: us-docker.pkg.dev/google-samples/containers/gke/gb-redis-follower:v2
resources:
requests:
cpu: 100m
memory: 100Mi
ports:
- containerPort: 6379-
Apply the Redis Deployment from the following
redis-follower-deployment.yamlfile:kubectl apply -f https://k8s.io/examples/application/guestbook/redis-follower-deployment.yaml -
Verify that the two Redis follower replicas are running by querying the list of Pods:
kubectl get podsThe response should be similar to this:
NAME READY STATUS RESTARTS AGE redis-follower-dddfbdcc9-82sfr 1/1 Running 0 37s redis-follower-dddfbdcc9-qrt5k 1/1 Running 0 38s redis-leader-fb76b4755-xjr2n 1/1 Running 0 11m
Creating the Redis follower service
The guestbook application needs to communicate with the Redis followers to read data. To make the Redis followers discoverable, you must set up another Service.
# SOURCE: https://cloud.google.com/kubernetes-engine/docs/tutorials/guestbook
apiVersion: v1
kind: Service
metadata:
name: redis-follower
labels:
app: redis
role: follower
tier: backend
spec:
ports:
# the port that this service should serve on
- port: 6379
selector:
app: redis
role: follower
tier: backend-
Apply the Redis Service from the following
redis-follower-service.yamlfile:kubectl apply -f https://k8s.io/examples/application/guestbook/redis-follower-service.yaml -
Query the list of Services to verify that the Redis Service is running:
kubectl get serviceThe response should be similar to this:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 3d19h redis-follower ClusterIP 10.110.162.42 <none> 6379/TCP 9s redis-leader ClusterIP 10.103.78.24 <none> 6379/TCP 6m10s
Note:
This manifest file creates a Service namedredis-follower with a set of
labels that match the labels previously defined, so the Service routes network
traffic to the Redis Pod.Set up and Expose the Guestbook Frontend
Now that you have the Redis storage of your guestbook up and running, start the guestbook web servers. Like the Redis followers, the frontend is deployed using a Kubernetes Deployment.
The guestbook app uses a PHP frontend. It is configured to communicate with either the Redis follower or leader Services, depending on whether the request is a read or a write. The frontend exposes a JSON interface, and serves a jQuery-Ajax-based UX.
Creating the Guestbook Frontend Deployment
# SOURCE: https://cloud.google.com/kubernetes-engine/docs/tutorials/guestbook
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
spec:
replicas: 3
selector:
matchLabels:
app: guestbook
tier: frontend
template:
metadata:
labels:
app: guestbook
tier: frontend
spec:
containers:
- name: php-redis
image: us-docker.pkg.dev/google-samples/containers/gke/gb-frontend:v5
env:
- name: GET_HOSTS_FROM
value: "dns"
resources:
requests:
cpu: 100m
memory: 100Mi
ports:
- containerPort: 80
-
Apply the frontend Deployment from the
frontend-deployment.yamlfile:kubectl apply -f https://k8s.io/examples/application/guestbook/frontend-deployment.yaml -
Query the list of Pods to verify that the three frontend replicas are running:
kubectl get pods -l app=guestbook -l tier=frontendThe response should be similar to this:
NAME READY STATUS RESTARTS AGE frontend-85595f5bf9-5tqhb 1/1 Running 0 47s frontend-85595f5bf9-qbzwm 1/1 Running 0 47s frontend-85595f5bf9-zchwc 1/1 Running 0 47s
Creating the Frontend Service
The Redis Services you applied is only accessible within the Kubernetes
cluster because the default type for a Service is
ClusterIP.
ClusterIP provides a single IP address for the set of Pods the Service is
pointing to. This IP address is accessible only within the cluster.
If you want guests to be able to access your guestbook, you must configure the
frontend Service to be externally visible, so a client can request the Service
from outside the Kubernetes cluster. However a Kubernetes user can use
kubectl port-forward to access the service even though it uses a
ClusterIP.
Note:
Some cloud providers, like Google Compute Engine or Google Kubernetes Engine, support external load balancers. If your cloud provider supports load balancers and you want to use it, uncommenttype: LoadBalancer.# SOURCE: https://cloud.google.com/kubernetes-engine/docs/tutorials/guestbook
apiVersion: v1
kind: Service
metadata:
name: frontend
labels:
app: guestbook
tier: frontend
spec:
# if your cluster supports it, uncomment the following to automatically create
# an external load-balanced IP for the frontend service.
# type: LoadBalancer
#type: LoadBalancer
ports:
# the port that this service should serve on
- port: 80
selector:
app: guestbook
tier: frontend-
Apply the frontend Service from the
frontend-service.yamlfile:kubectl apply -f https://k8s.io/examples/application/guestbook/frontend-service.yaml -
Query the list of Services to verify that the frontend Service is running:
kubectl get servicesThe response should be similar to this:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE frontend ClusterIP 10.97.28.230 <none> 80/TCP 19s kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 3d19h redis-follower ClusterIP 10.110.162.42 <none> 6379/TCP 5m48s redis-leader ClusterIP 10.103.78.24 <none> 6379/TCP 11m
Viewing the Frontend Service via kubectl port-forward
-
Run the following command to forward port
8080on your local machine to port80on the service.kubectl port-forward svc/frontend 8080:80The response should be similar to this:
Forwarding from 127.0.0.1:8080 -> 80 Forwarding from [::1]:8080 -> 80 -
load the page http://localhost:8080 in your browser to view your guestbook.
Viewing the Frontend Service via LoadBalancer
If you deployed the frontend-service.yaml manifest with type: LoadBalancer
you need to find the IP address to view your Guestbook.
-
Run the following command to get the IP address for the frontend Service.
kubectl get service frontendThe response should be similar to this:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE frontend LoadBalancer 10.51.242.136 109.197.92.229 80:32372/TCP 1m -
Copy the external IP address, and load the page in your browser to view your guestbook.
Note:
Try adding some guestbook entries by typing in a message, and clicking Submit. The message you typed appears in the frontend. This message indicates that data is successfully added to Redis through the Services you created earlier.Scale the Web Frontend
You can scale up or down as needed because your servers are defined as a Service that uses a Deployment controller.
-
Run the following command to scale up the number of frontend Pods:
kubectl scale deployment frontend --replicas=5 -
Query the list of Pods to verify the number of frontend Pods running:
kubectl get podsThe response should look similar to this:
NAME READY STATUS RESTARTS AGE frontend-85595f5bf9-5df5m 1/1 Running 0 83s frontend-85595f5bf9-7zmg5 1/1 Running 0 83s frontend-85595f5bf9-cpskg 1/1 Running 0 15m frontend-85595f5bf9-l2l54 1/1 Running 0 14m frontend-85595f5bf9-l9c8z 1/1 Running 0 14m redis-follower-dddfbdcc9-82sfr 1/1 Running 0 97m redis-follower-dddfbdcc9-qrt5k 1/1 Running 0 97m redis-leader-fb76b4755-xjr2n 1/1 Running 0 108m -
Run the following command to scale down the number of frontend Pods:
kubectl scale deployment frontend --replicas=2 -
Query the list of Pods to verify the number of frontend Pods running:
kubectl get podsThe response should look similar to this:
NAME READY STATUS RESTARTS AGE frontend-85595f5bf9-cpskg 1/1 Running 0 16m frontend-85595f5bf9-l9c8z 1/1 Running 0 15m redis-follower-dddfbdcc9-82sfr 1/1 Running 0 98m redis-follower-dddfbdcc9-qrt5k 1/1 Running 0 98m redis-leader-fb76b4755-xjr2n 1/1 Running 0 109m
Cleaning up
Deleting the Deployments and Services also deletes any running Pods. Use labels to delete multiple resources with one command.
-
Run the following commands to delete all Pods, Deployments, and Services.
kubectl delete deployment -l app=redis kubectl delete service -l app=redis kubectl delete deployment frontend kubectl delete service frontendThe response should look similar to this:
deployment.apps "redis-follower" deleted deployment.apps "redis-leader" deleted deployment.apps "frontend" deleted service "frontend" deleted -
Query the list of Pods to verify that no Pods are running:
kubectl get podsThe response should look similar to this:
No resources found in default namespace.
What's next
-
Complete the Kubernetes Basics Interactive Tutorials
-
Use Kubernetes to create a blog using Persistent Volumes for MySQL and Wordpress
-
Read more about connecting applications with services
-
Read more about using labels effectively
-
Try Deploy a Canary Release to learn how to safely test new application versions in production.