Deploy Stages
A deploy stage pushes your built and tested artifact to a target environment like staging or production.
The deploy stage is the payoff of the pipeline — it delivers your tested build to a real environment.
Deployment patterns
- Push to a server — copy files over SSH and restart a service.
- Deploy to Kubernetes —
kubectl applyorhelm upgrade. - Cloud platform — deploy to AWS, Azure, Heroku, etc.
Guarding deploys
Protect deploys with when { branch 'main' } and, for production, an input approval step. Deploy to staging automatically, but require a human to approve production.
Example
pipeline {
agent any
stages {
stage('Deploy to Staging') {
when { branch 'main' }
steps {
sh 'kubectl apply -f k8s/staging/ --namespace staging'
}
}
stage('Approve Production') {
when { branch 'main' }
steps {
input message: 'Deploy to production?', ok: 'Ship it'
}
}
stage('Deploy to Production') {
when { branch 'main' }
steps {
sh 'kubectl apply -f k8s/production/ --namespace production'
}
}
}
}When to use it
- A pipeline deploys to staging automatically on every green build from main and waits for manual approval before production.
- A Helm upgrade step in the deploy stage passes image tags as values so Kubernetes rolls out only the new image.
- A deploy stage uses a when condition to skip production deployment on non-main branches during pull request builds.
More examples
Staging and production deploy stages
Deploys to staging, waits for a manual approval gate, then deploys the same image to production.
stage('Deploy Staging') {
steps {
sh "helm upgrade --install myapp ./chart --set image.tag=${BUILD_NUMBER} -n staging"
}
}
stage('Approve Production') {
steps { input 'Deploy to production?' }
}
stage('Deploy Production') {
steps {
sh "helm upgrade --install myapp ./chart --set image.tag=${BUILD_NUMBER} -n production"
}
}SSH deploy to a remote server
SSHes to a production server, pulls the new Docker image, and restarts services with Docker Compose.
stage('Deploy to Server') {
steps {
withCredentials([sshUserPrivateKey(
credentialsId: 'prod-server-key',
keyFileVariable: 'SSH_KEY',
usernameVariable: 'SSH_USER'
)]) {
sh """
ssh -i $SSH_KEY [email protected] \\
'docker pull registry/myapp:${BUILD_NUMBER} && \\
docker-compose up -d'
"""
}
}
}Conditional deploy on main branch
Runs the Kubernetes rolling update only on the main branch and waits for the rollout to complete.
stage('Deploy Production') {
when { branch 'main' }
steps {
sh """
kubectl set image deployment/myapp \\
app=registry/myapp:${BUILD_NUMBER} \\
-n production
kubectl rollout status deployment/myapp -n production
"""
}
}
Discussion