The CD pipeline from the previous lesson takes every release all the way to production, but it does so in the most naive way possible: it restarts prod-01 and then prod-02 while the lb.tecnoshop.local load balancer keeps sending them traffic, and if the new version does not start on prod-01, the build fails and leaves that server broken. Deploying frequently only makes sense if every deployment is boring: no interruptions for customers and a fast, tested way back. In this lesson you will compare deployment strategies, implement a rolling deployment that takes each node out of the load balancer before touching it, add post-deployment verification and an automatic rollback that never leaves a node half-done, create the orders-api-rollback job to roll back by hand in minutes, and see how to handle database migrations and deployment windows.
What Is Wrong with the Current Deployment
| Problem | Consequence |
|---|---|
prod-01 is restarted while it is receiving traffic |
During the seconds it takes Spring Boot to start, the requests the load balancer sends it fail |
| In-flight requests are cut off | A customer who was creating an order gets an error |
If the health check on prod-01 fails, the build stops |
prod-01 is left with a version that does not start, and the load balancer keeps sending it traffic until it marks it as down |
| Nothing records how to go back | Someone has to log in over SSH, remember which jar was there and switch the link by hand |
Deployment Strategies
| Strategy | How it works | Risk for users | Infrastructure cost | Complexity | Rollback time |
|---|---|---|---|---|---|
| Recreate | All instances are stopped and started again with the new version | High: a full outage during startup | No extra cost | Very low | Minutes (another deployment) |
| Rolling | Instances are updated one at a time (or in batches), taking each one out of the load balancer | Low; two versions coexist during the deployment | No extra cost (reduced capacity while a node is out) | Medium | Minutes (revert node by node) |
| Blue/green | Two complete environments; you deploy to the idle one ("green") and switch all the traffic at once | Very low; the switch is instantaneous | High: double the capacity | Medium-high | Seconds (send the traffic back to "blue") |
| Canary | The new version first receives a small fraction of the traffic; if its metrics are good, the share is increased | Very low: a failure affects few users | Medium | High: it requires reliable metrics and an automated decision | Seconds (withdraw the canary) |
| Feature flags | The new code is deployed switched off and turned on through configuration, for some users or for all of them | Very low for the feature | Low (a flag service or library) | Medium; old flags are technical debt | Seconds (turn the flag off) |
The first four decide how the binary reaches the servers; feature flags separate deploying (installing the code) from releasing (letting users see it), and they can be combined with any of the others. Libraries such as Togglz (Java), standards such as OpenFeature and services such as Unleash make this easier.
For TecnoShop, with two servers behind nginx: rolling. It uses the infrastructure that already exists, eliminates the outage and, together with automatic rollback, limits the damage of a faulty version to one node out of the load balancer. Blue/green and canary are explained in section 8 as the next step.
The lb.tecnoshop.local Load Balancer
lb.tecnoshop.local runs nginx (the open source version) and spreads requests across the two servers. Open source nginx has no API for changing its configuration on the fly, so taking a node out means editing the configuration and reloading it with nginx -s reload. The reload is graceful: the old worker processes finish the requests they were handling and the new ones apply the new configuration, without dropping connections.
The Configuration
/etc/nginx/conf.d/orders-api.conf, installed by the platform team:
include /etc/nginx/orders-api/upstream.conf;
server {
listen 80;
server_name lb.tecnoshop.local orders-api.tecnoshop.local;
location / {
proxy_pass http://orders_api;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 2s;
proxy_next_upstream error timeout http_502 http_503;
}
}include .../upstream.conf: the server group lives in a separate file that a script can regenerate without touching the rest. It goes outside theserverblock becauseupstreambelongs to thehttpcontext (the files inconf.d/are included inside it).proxy_pass http://orders_api: forwards requests to theorders_apigroup.proxy_http_version 1.1andConnection "": required to reuse connections to the servers (keepalive).proxy_connect_timeout 2sandproxy_next_upstream: if a server does not accept the connection or responds 502/503, nginx retries the request on the other one. By default, nginx does not retry non-idempotent requests (such as aPOSTthat creates an order) once they have been sent, and that is the right behavior: we do not want duplicate orders.
/etc/nginx/orders-api/upstream.conf, in its normal state:
# Generated by orders-api-lb. Do not edit by hand.
upstream orders_api {
server prod-01.tecnoshop.local:8081 max_fails=3 fail_timeout=10s;
server prod-02.tecnoshop.local:8081 max_fails=3 fail_timeout=10s;
keepalive 16;
}max_fails=3 fail_timeout=10s: a passive health check: after three failures within 10 seconds, nginx stops sending traffic to that server for 10 seconds. It is a safety net, not a deployment mechanism: it detects the problem after some users have already suffered it.- To take a node out deliberately, its line becomes
server prod-01.tecnoshop.local:8081 down;: nginx sends it nothing.
The Load Balancer Script
The pipeline does not edit nginx files over SSH: it calls a single program, installed by the platform team on the load balancer, which validates what it is asked to do. /usr/local/sbin/orders-api-lb (owner root, permissions 0755):
#!/bin/sh
# Installed by the platform team on lb.tecnoshop.local.
# Usage: orders-api-lb remove|restore <node> | orders-api-lb status
set -eu
NODES="prod-01.tecnoshop.local prod-02.tecnoshop.local"
STATE_DIR=/var/lib/orders-api-lb
UPSTREAM=/etc/nginx/orders-api/upstream.conf
ACTION="${1:-}"
NODE="${2:-}"
known=no
for n in $NODES; do
if [ "$n" = "$NODE" ]; then known=yes; fi
done
case "$ACTION" in
remove|restore) if [ "$known" != yes ]; then echo "Unknown node: '$NODE'" >&2; exit 2; fi ;;
status) ;;
*) echo "Usage: orders-api-lb remove|restore <node> | status" >&2; exit 2 ;;
esac
mkdir -p "$STATE_DIR"
if [ "$ACTION" = remove ]; then
active=0
for n in $NODES; do
if [ "$n" != "$NODE" ] && [ ! -e "$STATE_DIR/$n.out" ]; then active=$((active + 1)); fi
done
if [ "$active" -eq 0 ]; then
echo "ERROR: not removing $NODE: it is the last active node" >&2
exit 3
fi
touch "$STATE_DIR/$NODE.out"
elif [ "$ACTION" = restore ]; then
rm -f "$STATE_DIR/$NODE.out"
fi
if [ "$ACTION" != status ]; then
NEW_CONF=$(mktemp)
{
echo "# Generated by orders-api-lb. Do not edit by hand."
echo "upstream orders_api {"
for n in $NODES; do
if [ -e "$STATE_DIR/$n.out" ]; then
echo " server $n:8081 down;"
else
echo " server $n:8081 max_fails=3 fail_timeout=10s;"
fi
done
echo " keepalive 16;"
echo "}"
} > "$NEW_CONF"
cp "$UPSTREAM" "$UPSTREAM.previous"
install -m 0644 "$NEW_CONF" "$UPSTREAM"
rm -f "$NEW_CONF"
if ! nginx -t -q; then
cp "$UPSTREAM.previous" "$UPSTREAM"
echo "ERROR: the nginx configuration is not valid; the previous one has been restored" >&2
exit 4
fi
nginx -s reload
fi
for n in $NODES; do
if [ -e "$STATE_DIR/$n.out" ]; then echo "$n OUT"; else echo "$n ACTIVE"; fi
done- Allowlist: it only accepts the nodes in
NODESand three actions. Anything else ends with an error. - It never leaves the service without nodes:
removerefuses if the node is the last active one. - The state (which nodes are out) is stored as
<node>.outfiles in/var/lib/orders-api-lb, andupstream.confis regenerated in full from it: there are no partial edits that could be left half-done. nginx -tbefore reloading: if the resulting configuration is not valid, it restores the previous one and does not reload.- At the end it prints the state of each node, which is useful in the Jenkins console.
And in the load balancer's /etc/sudoers.d/deploy (edited with visudo), the only permission of the deploy user:
The ssh-production public key is in the authorized_keys of deploy on the load balancer, as on prod-01 and prod-02. With it you can take orders-api nodes out and put them back; nothing else.
Optional Lab: The lb Container
Create ~/tecnoshop-jenkins/lab/lb/ with orders-api.conf, upstream.conf and orders-api-lb (the three files above), sshd-tecnoshop.conf and sudoers-deploy (copied from dev-01, replacing the sudoers line with the one from the previous section), authorized_keys (a copy of ssh-production.pub) and this Dockerfile:
# LAB ONLY: simulates lb.tecnoshop.local (nginx + SSH in the same container)
FROM nginx:stable
RUN apt-get update \
&& apt-get install -y --no-install-recommends openssh-server sudo \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /run/sshd /etc/nginx/orders-api /var/lib/orders-api-lb /home/deploy/.ssh \
&& ssh-keygen -A \
&& useradd --create-home --shell /bin/bash deploy \
&& chown deploy:deploy /home/deploy/.ssh \
&& chmod 700 /home/deploy/.ssh \
&& rm -f /etc/nginx/conf.d/default.conf
COPY sshd-tecnoshop.conf /etc/ssh/sshd_config.d/tecnoshop.conf
COPY sudoers-deploy /etc/sudoers.d/deploy
COPY orders-api.conf /etc/nginx/conf.d/orders-api.conf
COPY upstream.conf /etc/nginx/orders-api/upstream.conf
COPY orders-api-lb /usr/local/sbin/orders-api-lb
COPY --chown=deploy:deploy authorized_keys /home/deploy/.ssh/authorized_keys
RUN chmod 440 /etc/sudoers.d/deploy \
&& chmod 755 /usr/local/sbin/orders-api-lb \
&& chmod 600 /home/deploy/.ssh/authorized_keys
CMD ["sh", "-c", "/usr/sbin/sshd -e && exec nginx -g 'daemon off;'"]FROM nginx:stable: the official nginx image (based on Debian). As in 05-04, for real use you would pin a specific version.rm -f .../default.conf: removes the welcome site so thatorders-api.confhandles port 80.CMD: startssshdin the background and then nginx in the foreground. Two processes in one container is a lab shortcut; a real load balancer is a machine (or a managed service).
In docker-compose.yml, just like dev-01: build: ./lab/lb, image: tecnoshop/lab-lb:1, container_name: lb, hostname: lb.tecnoshop.local and the network alias lb.tecnoshop.local. Start it with docker compose up -d --build lb, register its host key in deploy/known_hosts and test it from the agent: docker compose exec linux-agent-01 curl -s http://lb.tecnoshop.local/actuator/info.
The Deployment Scripts, Revisited
The deploy/ directory of orders-api now looks like this:
| File | What it does | Status |
|---|---|---|
deploy.sh <server> |
Copies the jar, keeps the previous version, activates the new one, restarts and checks | Revised |
check-health.sh <base-url> [version] |
Waits for UP and, if given, checks the version in /actuator/info |
New |
revert.sh <server> [version] |
Activates the previous version (or the one given), restarts and checks | New |
load-balancer.sh remove|restore|status [node] |
Calls orders-api-lb on the load balancer over SSH |
New |
fetch-release.sh <version> |
Downloads and verifies the release from Nexus | From 07-03 |
known_hosts, orders-api.service |
Host keys and systemd unit | Extended with lb |
check-health.sh
#!/bin/sh
# Waits for orders-api to respond UP and, if given, checks that it is running the expected version.
# Usage: deploy/check-health.sh <base-url> [expected-version]
set -eu
BASE="$1"
EXPECTED="${2:-}"
attempt=1
until curl -sf "$BASE/actuator/health" | grep -q '"status":"UP"'; do
if [ "$attempt" -ge 30 ]; then
echo "ERROR: orders-api is not responding UP on $BASE after 60 seconds"
exit 1
fi
attempt=$((attempt + 1))
sleep 2
done
if [ -n "$EXPECTED" ]; then
INFO=$(curl -sf "$BASE/actuator/info" || true)
case "$INFO" in
*"\"version\":\"$EXPECTED\""*) ;;
*'"version":'*) echo "ERROR: $BASE is responding, but not with version $EXPECTED: $INFO"; exit 1 ;;
*) echo "WARNING: $BASE does not publish its version in /actuator/info (jar older than 07-02)" ;;
esac
fi
echo "OK: orders-api is responding UP on $BASE${EXPECTED:+ with version $EXPECTED} (attempt $attempt)"- The
untilloop is the same one from 06-06, extracted so thatdeploy.sh,revert.shand the Jenkins jobs can use it. - The version check catches a subtle case: the link has been switched, but the old process (or a process that is not the expected one) is still responding. Jars built before
build-info(07-02) do not publish their version: the script warns without failing, so that you can still go back to them. ${EXPECTED:+ with version $EXPECTED}: adds the text only if the variable has a value.
deploy.sh, Revised
#!/bin/sh
# Deploys the orders-api jar to a server over SSH and checks its health.
# Usage: deploy/deploy.sh <server>
# Requires: the SSH key loaded and APP_VERSION plus BUILD_NUMBER, or DEPLOY_VERSION.
set -eu
SERVER="$1"
DEPLOY_USER="deploy"
LOCAL_JAR=$(ls target/orders-api-*.jar)
DEPLOY_VERSION="${DEPLOY_VERSION:-${APP_VERSION}-${BUILD_NUMBER}}"
RELEASE_PATH="/opt/orders-api/releases/orders-api-${DEPLOY_VERSION}.jar"
SSH_OPTS="-o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=deploy/known_hosts -o ConnectTimeout=10"
echo "==> Copying $LOCAL_JAR to $SERVER:$RELEASE_PATH"
scp $SSH_OPTS "$LOCAL_JAR" "$DEPLOY_USER@$SERVER:$RELEASE_PATH"
echo "==> Activating version $DEPLOY_VERSION on $SERVER"
ssh $SSH_OPTS "$DEPLOY_USER@$SERVER" "
set -e
cd /opt/orders-api
CURRENT=\$(readlink orders-api.jar || true)
if [ -n \"\$CURRENT\" ] && [ \"\$CURRENT\" != '$RELEASE_PATH' ]; then
ln -sfn \"\$CURRENT\" orders-api.jar.previous
fi
ln -sfn '$RELEASE_PATH' orders-api.jar
sudo systemctl restart orders-api.service
PREVIOUS=\$(readlink orders-api.jar.previous || true)
ls -1t releases/orders-api-*.jar | tail -n +6 | while read -r f; do
if [ \"/opt/orders-api/\$f\" != \"\$PREVIOUS\" ]; then rm -f \"\$f\"; fi
done
"
if ! sh deploy/check-health.sh "http://$SERVER:8081" "$APP_VERSION"; then
ssh $SSH_OPTS "$DEPLOY_USER@$SERVER" "systemctl status orders-api.service --no-pager" || true
exit 1
fiThe changes from 06-06:
- The
orders-api.jar.previouslink: before activating the new version, the script records where the active link was pointing. It is the server's "memory" for going back. If the same version is redeployed, it is not overwritten (otherwise "previous" and "current" would be the same). \$(...)and\": inside the double quotes of the remote command,\$makes the variable get evaluated on the server, while$RELEASE_PATH(no backslash) is substituted on the agent before the command is sent.- The cleanup protects the previous version: the 5 most recent versions are still kept, but the target of
orders-api.jar.previousis never deleted, even if it is older. - The check uses
check-health.shwith the expected version (APP_VERSION:1.1.0in CD,1.2.0-SNAPSHOTindev).
revert.sh
#!/bin/sh
# Takes orders-api on a server back to the previous version (or to a version present in releases/).
# Usage: deploy/revert.sh <server> [deploy-version]
set -eu
SERVER="$1"
TO_VERSION="${2:-}"
DEPLOY_USER="deploy"
SSH_OPTS="-o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=deploy/known_hosts -o ConnectTimeout=10"
case "$TO_VERSION" in
*[!0-9A-Za-z.-]*) echo "ERROR: invalid version: '$TO_VERSION'" >&2; exit 1 ;;
esac
echo "==> Reverting orders-api on $SERVER to ${TO_VERSION:-the previous version}"
ssh $SSH_OPTS "$DEPLOY_USER@$SERVER" "
set -e
cd /opt/orders-api
if [ -n '$TO_VERSION' ]; then
TARGET_JAR=/opt/orders-api/releases/orders-api-$TO_VERSION.jar
else
TARGET_JAR=\$(readlink orders-api.jar.previous || true)
fi
if [ -z \"\$TARGET_JAR\" ] || [ ! -f \"\$TARGET_JAR\" ]; then
echo \"ERROR: there is no version to go back to (\$TARGET_JAR)\" >&2
exit 1
fi
echo \"Active: \$(readlink orders-api.jar) -> switching to: \$TARGET_JAR\"
ln -sfn \"\$TARGET_JAR\" orders-api.jar
sudo systemctl restart orders-api.service
"
sh deploy/check-health.sh "http://$SERVER:8081"- Without a second argument, it goes back to the target of
orders-api.jar.previous; with one (1.1.0, or1.2.0-SNAPSHOT-57indev), to that version, if it is still inreleases/. - It does not swap the links: after reverting,
orders-api.jarandorders-api.jar.previouspoint to the same jar. Runningrevert.shtwice does not take you back to the faulty version; going forward is always a new deployment. - Validating the version rules out characters that could alter the remote command.
- It only checks health: the previous version may not publish its version.
load-balancer.sh
#!/bin/sh
# Removes, restores or queries an orders-api node on the load balancer.
# Usage: deploy/load-balancer.sh remove|restore|status [node]
set -eu
LOAD_BALANCER="${LOAD_BALANCER:-lb.tecnoshop.local}"
ACTION="$1"
NODE="${2:-}"
SSH_OPTS="-o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=deploy/known_hosts -o ConnectTimeout=10"
case "$ACTION" in remove|restore|status) ;; *) echo "Invalid action: $ACTION" >&2; exit 2 ;; esac
case "$NODE" in *[!a-z0-9.-]*) echo "Invalid node: $NODE" >&2; exit 2 ;; esac
echo "==> Load balancer $LOAD_BALANCER: $ACTION $NODE"
ssh $SSH_OPTS "deploy@$LOAD_BALANCER" "sudo /usr/local/sbin/orders-api-lb $ACTION $NODE"It validates locally before sending anything (defense in depth: the program on the load balancer validates too).
Rolling in ci/Jenkinsfile.cd: A Loop or One Stage per Node
For each node, the sequence is always the same:
flowchart LR
A["Remove from the load balancer"] --> B["Wait for draining<br/>(10 s)"]
B --> C["deploy.sh<br/>(copy, activate, restart)"]
C --> D{"Health and version OK?"}
D -->|"yes"| E["Put back into the load balancer"]
E --> F["Next node"]
D -->|"no"| G["Rollback: revert and restore<br/>the nodes already touched"]
There are two ways to express this in Jenkins:
| Option | Advantages | Drawbacks |
|---|---|---|
One stage per node (Production: prod-01, Production: prod-02) |
Each node is a box in Pipeline Graph View | Duplicated code; adding prod-03 means copying a stage; rolling back "the nodes already touched" is hard to express across stages |
A loop in script over PRODUCTION_NODES (TecnoShop) |
The list of nodes is data; the try/catch covers the whole deployment and knows which nodes have been touched |
A single box in the view; the detail is in the labels (label) of each sh |
TecnoShop chooses the loop: the number of nodes is configuration, not structure, and the rollback needs to see the deployment as a whole. To keep visibility, each sh carries a label with the node name, and Pipeline Graph View shows them inside the stage. The Groovy code just orchestrates: all the logic is in the scripts.
Two helper methods, defined at the top of Jenkinsfile.cd, before the pipeline block (the Groovy in a declarative Jenkinsfile allows file-level methods):
def updateNode(String nodeName) {
withEnv(["NODE=${nodeName}"]) {
sh label: "${nodeName}: remove from the load balancer", script: 'sh deploy/load-balancer.sh remove "$NODE"'
sleep time: 10, unit: 'SECONDS'
sh label: "${nodeName}: deploy and check", script: 'sh deploy/deploy.sh "$NODE"'
sh label: "${nodeName}: put back into the load balancer", script: 'sh deploy/load-balancer.sh restore "$NODE"'
}
}
def revertNode(String nodeName) {
withEnv(["NODE=${nodeName}"]) {
sh label: "${nodeName}: remove from the load balancer", script: 'sh deploy/load-balancer.sh remove "$NODE"'
sh label: "${nodeName}: go back to the previous version", script: 'sh deploy/revert.sh "$NODE"'
sh label: "${nodeName}: put back into the load balancer", script: 'sh deploy/load-balancer.sh restore "$NODE"'
}
}withEnv(["NODE=${nodeName}"]): the node name reaches the shell as an environment variable; theshsteps use single quotes and"$NODE", with no Groovy interpolation in the command (04-03). Interpolation only appears in thelabel, which is just text for the console.sleep time: 10: the draining. After nginx reloads, the requests that were already onprod-01finish; ten seconds is plenty for an API whose requests take milliseconds. On top of that, Spring Boot (since the 3.4 line) performs a graceful shutdown by default when it receivesSIGTERM: it stops accepting new requests and waits for the in-flight ones before stopping.- If any
shfails, the method throws the exception and the node stays out of the load balancer: a node with a version that does not start never receives traffic again.
Post-Deployment Verification and Automatic Rollback
The production stage:
stage('Deploy to production') {
agent {
label 'linux'
}
options {
lock(resource: 'env-production')
timeout(time: 20, unit: 'MINUTES')
}
steps {
milestone(label: 'Production')
script { env.CURRENT_ENV = 'production' }
unstash 'release'
sh label: 'Deployment window', script: 'sh ci/deploy-window.sh'
sshagent(credentials: ['ssh-production']) {
script {
List touched = []
try {
for (String nodeName : env.PRODUCTION_NODES.tokenize(' ')) {
touched << nodeName
updateNode(nodeName)
}
sh label: 'Production verification through the load balancer',
script: 'sh ci/acceptance.sh "http://$LOAD_BALANCER" "$APP_VERSION" production'
} catch (err) {
echo "Production failure: ${err}. Reverting, in reverse order: ${touched.reverse().join(', ')}"
List notReverted = []
for (String nodeName : touched.reverse()) {
try {
revertNode(nodeName)
} catch (revertErr) {
echo "ERROR: could not revert ${nodeName}; it stays OUT of the load balancer (${revertErr})"
notReverted << nodeName
}
}
env.REVERTED = notReverted ? "partial; not reverted: ${notReverted.join(', ')}" : 'yes'
throw err
}
}
}
}
post {
cleanup {
cleanWs()
}
}
}The behavior, case by case:
| What happens | Result |
|---|---|
Everything goes well on prod-01, prod-02 and the verification |
Production on the new version, with no outage. Green build |
The health check fails on prod-01 |
prod-01 is out of the load balancer; it is reverted, checked and put back. prod-02 has not been touched. Red build, REVERTED notice |
The health check fails on prod-02 |
prod-02 is reverted and then prod-01 (which already had the new version): production is not left running two different versions. REVERTED notice |
| The verification through the load balancer fails | Both nodes are reverted, one after the other, always with the other one serving |
| The rollback of a node fails as well | That node stays out of the load balancer and the other one serves. Red build, a notice naming the pending node: manual intervention |
Details:
touched << nodeNamebeforeupdateNode: a node counts as touched as soon as its update starts, because its link may have changed even if it fails later.- The post-deployment verification reuses
ci/acceptance.shfrom 07-03 against the load balancer (LOAD_BALANCER = 'lb.tecnoshop.local', port 80): Marta's same criteria, now in production and through the real path users take. They are read-onlyGETrequests, safe in production. Since each request may go to a different node, checking the version (A2) through the load balancer confirms that all of them respond with the new one. throw err: after reverting, the build ends red with the original error. A successful rollback is not a successful deployment.env.REVERTEDis read by the pipeline'spostsection to sendREVERTED(or the details of a partial rollback) instead ofFAILED.- The last active node is never removed: if
prod-01was left out because of a failed rollback,orders-api-lbwill refuse to removeprod-02, which will keep serving with whatever version it has. That is the right call: better a version we did not want than no service at all.
In staging, with a single server and no load balancer, automatic rollback is simpler: if deploy.sh fails, a post { failure { ... } } in the Deploy to staging stage runs revert.sh so that staging-01 stays usable for the other teams. If what fails is the acceptance tests, on the other hand, the version deliberately stays in staging: Marta and Diego need it to investigate.
Blue/Green and Canary with nginx: Why Not Yet
Blue/Green
Two complete copies of the service; the load balancer points to one (blue) while the other (green) is deployed and tested, and the switch is a single reload. On TecnoShop's two servers, that would mean two instances per server (for example, on ports 8081 and 8082, with two systemd units):
upstream orders_api_blue {
server prod-01.tecnoshop.local:8081;
server prod-02.tecnoshop.local:8081;
}
upstream orders_api_green {
server prod-01.tecnoshop.local:8082;
server prod-02.tecnoshop.local:8082;
}
# /etc/nginx/orders-api/active.conf contains a single line, which the deployment rewrites:
# proxy_pass http://orders_api_green;
# and the location block does: include /etc/nginx/orders-api/active.conf;- Advantages: rolling back means pointing
active.confback toblueand reloading, in a second; the green environment is tested in full before it receives real traffic. - Why TecnoShop is not adopting it yet: it doubles the memory needed on each server, doubles the units and the configuration, and its main advantage (an instant rollback) is fairly close to what the current rolling deployment offers, which reverts a node in under a minute. Once there is a database, moreover, both versions coexist against the same schema (section 11), just as with rolling.
Canary
upstream orders_api {
server prod-01.tecnoshop.local:8081 weight=9; # stable version: ~90% of requests
server prod-02.tecnoshop.local:8081 weight=1; # canary with the new version: ~10%
}weight: nginx's proportional distribution. You deploy the new version only toprod-02, give it a small weight, watch its metrics (error rate, latency) for a while and, if they are good, complete the deployment.- Why not yet: with two servers, the canary is half the fleet and the split is coarse; and, above all, the decision "are its metrics good?" requires
orders-apito publish application metrics (for example, with Micrometer and Actuator's Prometheus endpoint) and a clear rule for promoting or withdrawing. It is the natural next step, and on Kubernetes (08-02) there are tools that automate it.
What TecnoShop's rolling deployment already does is a modest form of canary: prod-01 is updated and verified before prod-02 is touched.
Manual Rollback: orders-api-rollback, Roll Back and Roll Forward
When a problem shows up after the deployment (an hour later, with a use case the tests did not cover), automatic rollback no longer applies. There are three paths:
| Path | What it is | Time | When |
|---|---|---|---|
Fast roll back with orders-api-rollback |
Take each node back, rolling, to the previous jar that is already on the server | 1-2 minutes (plus the confirmation) | A serious error in production: restore the service first, investigate afterward |
Redeploy an earlier version with orders-api-cd (VERSION=1.1.0) |
Take an earlier release through the whole chain: staging, acceptance, approval |
15-20 minutes plus the approval | The previous jar is no longer on the servers, or you want to go back several versions |
| Roll forward | Fix it, publish 1.1.2 and take it through the chain |
However long the fix takes, plus the chain | The failure is minor and the fix is quick and clear |
The usual practice among teams doing continuous delivery is to prefer rolling forward when possible (the chain is fast and the fix goes through all the tests), and to keep the fast roll back for when the service is degraded and every minute counts.
The orders-api-rollback Job
In the orders-delivery folder, a Pipeline job like orders-api-cd, with Script Path ci/Jenkinsfile.rollback. It uses the same ssh-production credential (the folder provides it) and the same lock, so it never overlaps with a deployment in progress.
pipeline {
agent none
options {
timestamps()
buildDiscarder(logRotator(numToKeepStr: '100'))
skipDefaultCheckout()
}
parameters {
string(name: 'TARGET_VERSION', defaultValue: '', trim: true,
description: 'Empty: the previous version on each node. Or a version present in releases/ on the servers (e.g. 1.1.0).')
string(name: 'REASON', defaultValue: '', trim: true,
description: 'Incident or reason for the rollback (required)')
}
environment {
PRODUCTION_NODES = 'prod-01.tecnoshop.local prod-02.tecnoshop.local'
LOAD_BALANCER = 'lb.tecnoshop.local'
}
stages {
stage('Validate parameters') {
steps {
script {
if (params.TARGET_VERSION && !(params.TARGET_VERSION ==~ /\d+\.\d+\.\d+/)) {
error "TARGET_VERSION must have the form X.Y.Z or be empty"
}
if (!params.REASON) {
error 'Give the reason for the rollback'
}
currentBuild.displayName = "#${env.BUILD_NUMBER} · ${params.TARGET_VERSION ?: 'previous'}"
}
}
}
stage('Confirmation') {
options {
timeout(time: 30, unit: 'MINUTES')
}
input {
message 'Revert orders-api in production?'
ok 'Revert production'
submitter 'laura,production-approvers'
submitterParameter 'CONFIRMED_BY'
}
steps {
script {
currentBuild.description = "Rollback to ${params.TARGET_VERSION ?: 'the previous version'} · ${params.REASON} · confirmed by ${env.CONFIRMED_BY}"
}
}
}
stage('Revert production') {
agent {
label 'linux'
}
options {
lock(resource: 'env-production')
timeout(time: 15, unit: 'MINUTES')
}
steps {
checkout scm
sshagent(credentials: ['ssh-production']) {
sh label: 'Rolling to the target version', script: '''
for node in $PRODUCTION_NODES; do
sh deploy/load-balancer.sh remove "$node"
sleep 10
sh deploy/revert.sh "$node" "$TARGET_VERSION"
sh deploy/load-balancer.sh restore "$node"
done
sh deploy/check-health.sh "http://$LOAD_BALANCER" "$TARGET_VERSION"
'''
}
}
post {
cleanup {
cleanWs()
}
}
}
}
}- No
@Libraryand no notifications of its own: in an emergency, the fewer dependencies the better. The team is informed by the person who triggers it, who is in the incident channel. (If you want,notifyDeploymentwithresult: 'REVERTED'fits in apost { success { ... } }block.) - Confirmation with
input, as in CD, but with a 30-minutetimeout: it is an emergency action that someone is dealing with right then. - No deployment window: rolling back is always allowed.
- No rollback of the rollback: if a node fails to revert, the
shstep ends with an error and that node stays out of the load balancer while the other one serves. It is a manual-intervention situation, and the log says exactly at which step. - Who can trigger it: the same roles as
orders-api-cd; who can confirm it, the samesubmitter. Triggering it quickly and confirming it quickly is what shortens the time to restore in the DORA metrics.
Which Version Is on Each Server?
Three sources, from most to least direct:
# 1. What the service itself says (from the agent or any machine on the network)
for s in prod-01 prod-02; do
printf '%s: ' "$s"; curl -s "http://$s.tecnoshop.local:8081/actuator/info"; echo
done
# 2. The active and previous links on the server (over SSH, with that environment's key)
ssh [email protected] 'ls -l /opt/orders-api/orders-api.jar /opt/orders-api/orders-api.jar.previous'
# 3. Which nodes are in the load balancer
sh deploy/load-balancer.sh status/actuator/inforesponds with the version that is running, thanks tobuild-infofrom 07-02; that is what matters.ls -lon the link tells you which jar will start at the next restart and which one arevert.shwould go back to.- And the history of
orders-api-cdandorders-api-rollbacktells you when and who changed it.
Database Migrations: Expand/Contract
orders-api keeps its orders in memory, but that will not always be the case. Once it has a database, any zero-downtime strategy (rolling, blue/green, canary) means that two versions of the code coexist against the same schema for a few minutes. And rolling back the jar does not undo a schema change.
The solution is the expand/contract pattern (also called parallel change): each incompatible schema change is split into backward-compatible steps, spread over several releases. For example, renaming the customer column to customer_name:
| Release | Schema (migration) | Code | Compatible with the previous version? |
|---|---|---|---|
1.3.0 (expand) |
Adds customer_name, copies the data |
Writes to both columns, reads from customer |
Yes: 1.2.x keeps using customer |
1.4.0 |
No changes | Reads from customer_name |
Yes: both columns are still up to date |
1.5.0 (contract) |
Drops customer |
Only uses customer_name |
Yes, with respect to 1.4.0 |
Versioned migration tools such as Flyway (files like V3__add_customer_name.sql applied in order and recorded in a database table) or Liquibase apply each step automatically and repeatably. The rules for combining them with the pipeline:
- Within a release, migrations only expand; they never drop or rename anything the previous version uses.
- They are applied once per environment, before or when the first instance starts, and they are tested in
stagingjust like the code. - Rolling back the jar is safe precisely because the schema is still compatible with the previous version.
- Destructive (contract) migrations go into a later release, once no instance of the version that needed the old structure remains.
Deployment Windows and Freezes
Even when deployments are boring, there are times when the business does not want any: TecnoShop's Black Friday, a financial close, or a Friday afternoon with half the team away. Two complementary mechanisms:
The regular window, checked by the pipeline with ci/deploy-window.sh:
#!/bin/sh
# Fails outside the production deployment window: Monday to Thursday, 9:00 to 17:00 (Madrid time).
# The platform team can disable it temporarily with the global property TECNOSHOP_WINDOW=disabled.
set -eu
if [ "${TECNOSHOP_WINDOW:-active}" = "disabled" ]; then
echo "WARNING: deployment window disabled by the platform team"
exit 0
fi
DAY=$(TZ=Europe/Madrid date +%u)
HOUR=$(TZ=Europe/Madrid date +%H)
if [ "$DAY" -le 4 ] && [ "$HOUR" -ge 9 ] && [ "$HOUR" -lt 17 ]; then
echo "Inside the deployment window (day $DAY, $HOUR h)"
else
echo "ERROR: outside the production deployment window (Monday to Thursday, 9:00-17:00, Madrid time)"
exit 1
fidate +%u: the day of the week, from 1 (Monday) to 7 (Sunday);+%H, the hour as two digits.TZ=Europe/Madridsets the time zone, as in thecronexpressions from 02-03.TECNOSHOP_WINDOW: a global property in Manage Jenkins → System → Global properties (04-03), which only an administrator can change. It is the "key" for an urgent deployment outside the window, and using it is recorded in Audit Trail (05-02).- It runs at the start of
Deploy to production, after thelock: the approval can be given at any time, but the deployment only happens inside the window.
An ad hoc freeze, without touching code: in Manage Jenkins → Lockable Resources, Laura reserves the env-production resource (the Reserve button). While it is reserved, any orders-api-cd or orders-api-rollback build that reaches production waits on the lock, without holding an executor, until she releases it (Unreserve). It is immediate, visible and reversible. For an emergency during the freeze, Laura can release the resource, let the rollback through and reserve it again.
The Complete ci/Jenkinsfile.cd
With rolling deployment, automatic rollback in production and in staging, verification through the load balancer and the deployment window. New or changed parts are marked // 07-04.
@Library('[email protected]') _
def updateNode(String nodeName) { // 07-04
withEnv(["NODE=${nodeName}"]) {
sh label: "${nodeName}: remove from the load balancer", script: 'sh deploy/load-balancer.sh remove "$NODE"'
sleep time: 10, unit: 'SECONDS'
sh label: "${nodeName}: deploy and check", script: 'sh deploy/deploy.sh "$NODE"'
sh label: "${nodeName}: put back into the load balancer", script: 'sh deploy/load-balancer.sh restore "$NODE"'
}
}
def revertNode(String nodeName) { // 07-04
withEnv(["NODE=${nodeName}"]) {
sh label: "${nodeName}: remove from the load balancer", script: 'sh deploy/load-balancer.sh remove "$NODE"'
sh label: "${nodeName}: go back to the previous version", script: 'sh deploy/revert.sh "$NODE"'
sh label: "${nodeName}: put back into the load balancer", script: 'sh deploy/load-balancer.sh restore "$NODE"'
}
}
pipeline {
agent none
options {
timestamps()
buildDiscarder(logRotator(numToKeepStr: '100'))
skipDefaultCheckout()
}
parameters {
string(name: 'VERSION', defaultValue: '', trim: true,
description: 'Release X.Y.Z published in maven-releases (e.g. 1.1.0). Never a SNAPSHOT.')
string(name: 'SHA256', defaultValue: '', trim: true,
description: 'SHA-256 of the jar tested in the tag build. Filled in by CI; empty when triggered by hand.')
}
environment {
NEXUS_URL = 'http://nexus:8081'
STAGING_SERVER = 'staging-01.tecnoshop.local'
PRODUCTION_NODES = 'prod-01.tecnoshop.local prod-02.tecnoshop.local'
LOAD_BALANCER = 'lb.tecnoshop.local' // 07-04
APP_VERSION = "${params.VERSION}"
DEPLOY_VERSION = "${params.VERSION}"
}
stages {
stage('Validate parameters') {
steps {
script {
if (!(params.VERSION ==~ /\d+\.\d+\.\d+/)) {
error "VERSION must have the form X.Y.Z (e.g. 1.1.0); received '${params.VERSION}'"
}
if (params.SHA256 && !(params.SHA256 ==~ /[0-9a-f]{64}/)) {
error 'SHA256, if given, must be 64 lowercase hexadecimal characters'
}
currentBuild.displayName = "#${env.BUILD_NUMBER} · ${params.VERSION}"
}
}
}
stage('Fetch release') {
agent {
label 'linux'
}
options {
timeout(time: 5, unit: 'MINUTES')
}
steps {
checkout scm
sh label: 'Download from Nexus and verify', script: 'sh deploy/fetch-release.sh "$APP_VERSION"'
fingerprint 'target/orders-api-*.jar'
stash name: 'release', includes: 'target/orders-api-*.jar,deploy/**,ci/**'
}
post {
cleanup {
cleanWs()
}
}
}
stage('Staging') {
agent {
label 'linux'
}
options {
lock(resource: 'env-staging')
timeout(time: 15, unit: 'MINUTES')
}
stages {
stage('Deploy to staging') {
steps {
milestone(label: 'Staging')
script { env.CURRENT_ENV = 'staging' }
unstash 'release'
sshagent(credentials: ['ssh-staging']) {
sh label: 'Deploy to staging-01 over SSH', script: 'sh deploy/deploy.sh "$STAGING_SERVER"'
}
}
post {
failure { // 07-04
sshagent(credentials: ['ssh-staging']) {
sh label: 'Rollback of staging-01', script: 'sh deploy/revert.sh "$STAGING_SERVER" || true'
}
}
}
}
stage('Acceptance tests') {
steps {
sh label: 'QA acceptance criteria',
script: 'sh ci/acceptance.sh "http://$STAGING_SERVER:8081" "$APP_VERSION" staging'
notifyDeployment application: 'orders-api', channel: '#ci-orders', environment: 'staging',
version: params.VERSION, result: 'PENDING'
}
}
}
post {
cleanup {
cleanWs()
}
}
}
stage('Approval') {
options {
timeout(time: 24, unit: 'HOURS')
}
input {
message 'Deploy the version validated in staging to production?'
ok 'Deploy to production'
submitter 'laura,production-approvers'
submitterParameter 'APPROVED_BY'
parameters {
string(name: 'CHANGE_REFERENCE', defaultValue: '',
description: 'Reference of the approved change and a short reason (e.g. CHG-2026-0142: filter orders by status)')
}
}
steps {
script {
if (!env.CHANGE_REFERENCE?.trim()) {
error 'Approval without a change reference: not deploying to production.'
}
env.APPROVAL = "${env.APPROVED_BY} (${env.CHANGE_REFERENCE.trim()})"
currentBuild.description = "orders-api ${params.VERSION} · approved by ${env.APPROVAL}"
}
}
}
stage('Deploy to production') {
agent {
label 'linux'
}
options {
lock(resource: 'env-production')
timeout(time: 20, unit: 'MINUTES')
}
steps {
milestone(label: 'Production')
script { env.CURRENT_ENV = 'production' }
unstash 'release'
sh label: 'Deployment window', script: 'sh ci/deploy-window.sh' // 07-04
sshagent(credentials: ['ssh-production']) {
script { // 07-04: rolling + rollback
List touched = []
try {
for (String nodeName : env.PRODUCTION_NODES.tokenize(' ')) {
touched << nodeName
updateNode(nodeName)
}
sh label: 'Production verification through the load balancer',
script: 'sh ci/acceptance.sh "http://$LOAD_BALANCER" "$APP_VERSION" production'
} catch (err) {
echo "Production failure: ${err}. Reverting, in reverse order: ${touched.reverse().join(', ')}"
List notReverted = []
for (String nodeName : touched.reverse()) {
try {
revertNode(nodeName)
} catch (revertErr) {
echo "ERROR: could not revert ${nodeName}; it stays OUT of the load balancer (${revertErr})"
notReverted << nodeName
}
}
env.REVERTED = notReverted ? "partial; not reverted: ${notReverted.join(', ')}" : 'yes'
throw err
}
}
}
}
post {
cleanup {
cleanWs()
}
}
}
}
post {
success {
notifyDeployment application: 'orders-api', channel: '#ci-orders', environment: 'production',
version: params.VERSION, detail: "Approved by ${env.APPROVAL}"
}
failure {
notifyDeployment application: 'orders-api', channel: '#ci-orders',
environment: env.CURRENT_ENV ?: 'preparation', version: params.VERSION,
result: env.REVERTED ? 'REVERTED' : 'FAILED', // 07-04
detail: env.REVERTED == 'yes' ? 'Automatic rollback completed' : env.REVERTED
}
aborted {
notifyDeployment application: 'orders-api', channel: '#ci-orders', environment: 'production',
version: params.VERSION, result: 'CANCELLED'
}
}
}Put the new scripts (check-health.sh, revert.sh, load-balancer.sh, ci/deploy-window.sh), the revised deploy.sh, the known_hosts with lb and the two Jenkinsfiles into a PR. CI also uses deploy.sh for dev-01: the PR build does not deploy, but the first main build after merging will exercise the new deploy.sh on dev before any release uses it in production.
Common Mistakes and Tips
- Restarting without taking the node out of the load balancer: nginx's passive checks (
max_fails) only react after real requests have failed. - Not waiting for draining: reloading nginx and restarting in the same second cuts off the requests that were in flight.
- Putting the node back before checking its health: the load balancer would send traffic to a version that may not start. The order is remove, deploy, check, put back.
- Reverting only the node that failed: if the second node fails, the first one already has the new version; leaving it like that means keeping in production a version that has not passed full verification.
- Editing
upstream.confby hand during an incident:orders-api-lbregenerates it from its state and will undo the change. Useorders-api-lb(orload-balancer.sh) when working by hand too. RejectedAccessExceptionwithtokenize,reverseorjoin: your installation does not allow them in the sandbox. Check In-process Script Approval (03-06) or replacetokenize(' ')withsplit(' ').- Trusting the rollback without testing it: a rollback that has never been run will not work on the day you need it. Test it in
stagingfrom time to time (exercise 1). - Tip: time a complete
orders-api-rollbackrun and write it down in the incident procedure. It is your reference time to restore.
Exercises
Exercise 1. With the complete lab, publish a 1.1.1 release with a configuration error that only shows up in production: a src/main/resources/application-production.properties file inside the jar with the line server.servlet.context-path=/orders (every path would then start with /orders). Take it through CD. Does it pass CI? And staging? Where does it fail, what does the pipeline do, and what state are prod-01, prod-02 and the load balancer left in? Then delete the file and publish 1.1.2 (roll forward).
Exercise 2. With 1.1.2 in production, trigger orders-api-rollback without TARGET_VERSION. While it runs, query http://lb.tecnoshop.local/actuator/info in a loop from the agent (while true; do curl -s ...; echo; sleep 0.5; done). Do you see any errors? Which version is on each node at the end, and what would happen if you triggered the rollback a second time?
Exercise 3. On Black Friday (a Friday), the product team asks to deploy an urgent fix, 1.1.3, during an active freeze (resource reserved) and outside the window. Describe the exact steps Laura would follow, what gets recorded and why each mechanism still makes sense even though it is bypassed.
Solutions
Solution 1. CI for the v1.1.1 tag passes: neither the tests nor Smoke activate the production profile, so the file is not applied. staging passes too, with the staging profile. (This is part of the lesson: each stage only sees its own environment's configuration, which is why verification in production is not redundant.) After approval, the rolling deployment removes prod-01 from the load balancer, deploys and restarts; the service starts, but /actuator/health responds 404 (it is now at /orders/actuator/health) and check-health.sh uses up its 30 attempts. updateNode throws the exception with prod-01 out of the load balancer, while prod-02, on 1.1.0, serves all the traffic. The catch reverts prod-01 (touched only contains prod-01): it removes it (it was already out), activates orders-api.jar.previous (1.1.0), checks its health and puts it back. The build ends red and the REVERTED notice with "Automatic rollback completed" reaches Slack. Production is left entirely on 1.1.0, with both nodes ACTIVE in load-balancer.sh status, and no user has seen an error. For the roll forward: delete the file, publish 1.1.2 with the release process and CD takes it all the way to production.
Solution 2. No errors should appear: at every moment, at least one node is in the load balancer and serving, and the responses alternate between 1.1.2 and 1.1.0 while the rolling run lasts (two versions coexist, as in any rolling deployment). Why 1.1.0 and not 1.1.1? Because 1.1.1 never stayed active: after the automatic rollback in exercise 1, prod-01 went back to 1.1.0 and prod-02 was not touched, so when 1.1.2 was deployed, the orders-api.jar.previous link on both pointed to 1.1.0. At the end, both nodes respond 1.1.0. If you trigger it a second time, revert.sh goes back to the target of orders-api.jar.previous, which is already the active jar (the links are not swapped), so it restarts the nodes on the same version: there is no functional effect, just two orderly restarts. To go back to 1.1.2, use orders-api-cd (or TARGET_VERSION=1.1.2 in the rollback, if the jar is still in releases/).
Solution 3. (1) The team publishes v1.1.3 with the normal process: the commit stage, staging and acceptance are not skipped. (2) Laura approves the input with the reference of the urgent change. The build reaches Deploy to production and waits on the lock because env-production is reserved. (3) Laura changes the global property TECNOSHOP_WINDOW to disabled and releases the reservation (Unreserve). The build takes the lock, deploy-window.sh warns that the window is disabled and the rolling deployment proceeds. (4) When it finishes, Laura sets TECNOSHOP_WINDOW=active again and reserves the resource once more. What gets recorded: in Audit Trail, the global configuration changes and who made them; in Lockable Resources, the reservation and its release; in the build, who approved it and with what reference, plus the warning that the window was disabled; in Slack, the deployment. The mechanisms still make sense because they turn the exception into a deliberate, authorized and visible act by a person with the right permissions, instead of something that happens by accident because someone triggered CD on a Friday afternoon.
Conclusion
Deploying to production no longer interrupts the service or leaves servers broken. You know the strategies (recreate, rolling, blue/green, canary and feature flags) with their risk, cost, complexity and rollback time, and why TecnoShop adopts rolling today on prod-01 and prod-02: orders-api-lb, on lb.tecnoshop.local, takes nodes out and puts them back by regenerating the nginx upstream with validation and a graceful reload, never leaving the service without nodes, and ci/Jenkinsfile.cd walks through the nodes in a loop that removes, drains, deploys, checks health and version and puts back, with a final verification through the load balancer. If something fails, the automatic rollback reverts every touched node in reverse order with deploy/revert.sh and the orders-api.jar.previous link, and no node with a dubious version ever receives traffic again; in staging, a failed deployment is reverted too. For problems that show up later, orders-api-rollback rolls back in minutes with a confirmation, and you know when to prefer rolling forward or redeploying with CD, how to find out which version is on each server, why database migrations must follow the expand/contract pattern and how to apply windows and freezes with ci/deploy-window.sh and Lockable Resources reservations. The chain is now fast and reliable; what remains is to make it secure: it must not let through secrets, dependencies with known vulnerabilities or unreviewed changes to its own code. That is the subject of the last lesson of the module, DevSecOps: Security in the Pipeline.
