To deploy multiple versions of an application in Kubernetes, you can create separate deployments for each version. Here’s a step-by-step guide on how to do this:
Step 1: Create Deployments for Each Version
You will create separate deployments for each version of your application. For example, let's say you have two versions: v1 and v2.
Deploy Version 1
Create a deployment for version 1 of your application:
# deployment-v1.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-v1
spec:
replicas: 3
selector:
matchLabels:
app: myapp
version: v1
template:
metadata:
labels:
app: myapp
version: v1
spec:
containers:
- name: myapp
image: myapp:v1
ports:
- containerPort: 8080
Deploy Version 2
Create a deployment for version 2 of your application:
# deployment-v2.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-v2
spec:
replicas: 3
selector:
matchLabels:
app: myapp
version: v2
template:
metadata:
labels:
app: myapp
version: v2
spec:
containers:
- name: myapp
image: myapp:v2
ports:
- containerPort: 8080
Step 2: Apply the Deployments
Use kubectl apply to create the deployments in your Kubernetes cluster:
kubectl apply -f deployment-v1.yaml
kubectl apply -f deployment-v2.yaml
Step 3: Expose Each Deployment as a Service
You need to create services to expose each deployment. This allows you to route traffic to the correct version.
Service for Version 1
# service-v1.yaml
apiVersion: v1
kind: Service
metadata:
name: myapp-v1-service
spec:
selector:
app: myapp
version: v1
ports:
- port: 80
targetPort: 8080
Service for Version 2
# service-v2.yaml
apiVersion: v1
kind: Service
metadata:
name: myapp-v2-service
spec:
selector:
app: myapp
version: v2
ports:
- port: 80
targetPort: 8080
Step 4: Apply the Services
Use kubectl apply to create the services:
kubectl apply -f service-v1.yaml
kubectl apply -f service-v2.yaml
Step 5: (Optional) Create an Ingress Resource
If you want to route traffic to these services using an Ingress resource, you can create an Ingress definition. Here’s an example:
# ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: myapp-ingress
spec:
rules:
- host: myapp.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: myapp-v1-service
port:
number: 80
Step 6: Apply the Ingress
Use kubectl apply to create the Ingress:
kubectl apply -f ingress.yaml
Summary
By following these steps, you can successfully deploy multiple versions of an application in Kubernetes. Each version is managed independently through its own deployment and service, allowing you to control traffic and perform canary deployments or blue-green deployments as needed.
