
Deploying a new version of an application shouldn't mean taking your website offline. However, traditional deployments often require stopping the existing application, replacing its code, installing dependencies, and restarting the server. During this process, users may experience downtime, failed requests, or temporary service interruptions.
Zero-downtime deployment solves this problem by allowing the existing version of an application to continue serving traffic while a new version is prepared. Once the new version is running and passes its health checks, traffic is switched to it.
In this guide, we'll build a practical deployment workflow using Docker, GitHub Actions, and Nginx. We'll implement a blue-green deployment strategy, automate deployments through CI/CD, and discuss production best practices.
What Is a Zero-Downtime Deployment?
A zero-downtime deployment is a release strategy designed to update an application without interrupting service for users.
Instead of stopping the current application before starting the new version, we keep the existing version running until the replacement is ready.
For example, imagine your Node.js application currently runs version 1.0. You want to deploy version 2.0.
A traditional deployment might look like this:
Stop version 1.0.
Replace the application code.
Install or update dependencies.
Start version 2.0.
Wait for the application to become available.
During this process, requests may fail.
A zero-downtime deployment follows a different approach:
Keep version 1.0 running.
Start version 2.0 separately.
Verify that version 2.0 is healthy.
Switch traffic to version 2.0.
Allow existing requests to finish.
Stop version 1.0 after it is no longer needed.
This approach minimizes interruptions during releases.
Important: Zero downtime cannot be guaranteed in every situation. Application failures, database migrations, infrastructure problems, and long-running requests can still cause interruptions. The goal is to design the deployment process to avoid routine service interruptions.
Technologies Used
We'll use the following technologies:
Docker: Packages the application and its dependencies into a container.
GitHub Actions: Builds the Docker image and automates deployment.
Nginx: Acts as a reverse proxy and directs incoming requests to the active application.
Docker Hub: Stores versioned Docker images.
Node.js and Express: Provide a sample backend application.
Linux VPS: Hosts the application, Docker containers, and Nginx.
Our example uses a single VPS with two application instances. This is a practical starting point for small and medium-sized applications.
Understanding the Blue-Green Deployment Strategy
Blue-green deployment uses two application environments:
Blue: The currently active application.
Green: The new application version being prepared.
Only one environment receives normal production traffic at a time.
Suppose Blue is running version 1.0. When version 2.0 is ready, we start it in Green and test it independently.
After the health check succeeds, we update Nginx to send traffic to Green.
The deployment flow looks like this:
Developer pushes code
|
v
GitHub Actions
|
v
Build Docker Image
|
v
Push to Registry
|
v
Deploy to VPS
|
v
Start Inactive Container
|
v
Health Check
|
+--------+--------+
| |
Failed Passed
| |
v v
Keep Old App Update Nginx
|
v
Graceful Reload
|
v
New App Receives
TrafficThe key idea is that the currently active application remains available while the new container starts.
Step 1: Create a Sample Node.js Application
Let's create a simple Express application that exposes an API endpoint and a health-check endpoint.
Create a project directory:
mkdir zero-downtime-demo
cd zero-downtime-demoInitialize the Node.js project:
npm init -y
npm install expressCreate an app.js file:
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;
const APP_VERSION = process.env.APP_VERSION || "1.0.0";
app.get("/", (req, res) => {
res.json({
message: "Application is running",
version: APP_VERSION,
});
});
app.get("/health", (req, res) => {
res.status(200).json({
status: "healthy",
version: APP_VERSION,
});
});
const server = app.listen(PORT, "0.0.0.0", () => {
console.log(`Application running on port ${PORT}`);
});
// Handle termination signals gracefully.
process.on("SIGTERM", () => {
console.log("SIGTERM received. Closing server...");
server.close((error) => {
if (error) {
console.error("Error while closing server:", error);
process.exit(1);
}
console.log("Server closed successfully");
process.exit(0);
});
// Prevent the process from waiting indefinitely.
setTimeout(() => {
console.error("Graceful shutdown timed out");
process.exit(1);
}, 10000).unref();
});The /health endpoint allows the deployment system to verify whether the application is responding.
The SIGTERM handler helps the application stop gracefully when Docker terminates a container.
For production applications, also account for active requests, database connections, background jobs, and other resources that must be closed safely.
Step 2: Create a Dockerfile
Create a file named Dockerfile:
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY app.js ./
ENV NODE_ENV=production
ENV PORT=3000
EXPOSE 3000
CMD ["node", "app.js"]This Dockerfile uses a Node.js Alpine image, installs production dependencies, copies the application code, and starts the server.
For a production project, use a currently supported Node.js release and pin image versions appropriately. You can also use a non-root user, a multi-stage build, and additional image-hardening measures.
Create a .dockerignore file:
node_modules
.git
.env
coverage
npm-debug.logThis prevents unnecessary files and local secrets from being included in the Docker build context.
Step 3: Build and Test the Docker Image Locally
Build the image:
docker build -t zero-downtime-demo:local .Run a test container:
docker run -d \
--name zero-downtime-test \
-p 3000:3000 \
-e APP_VERSION=1.0.0 \
zero-downtime-demo:localTest the application:
curl http://localhost:3000/Expected response:
{
"message": "Application is running",
"version": "1.0.0"
}Check the health endpoint:
curl http://localhost:3000/healthIf both requests succeed, your application is ready for the next step.
Remove the test container:
docker rm -f zero-downtime-testStep 4: Configure Nginx as a Reverse Proxy
Nginx receives incoming HTTP requests and forwards them to the active application container.
We'll run two application instances on the VPS:
Blue:
127.0.0.1:3001Green:
127.0.0.1:3002
Nginx will initially direct requests to Blue.
Create an Nginx configuration file named app.conf:
upstream node_application {
server 127.0.0.1:3001;
keepalive 32;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://node_application;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
}
}Replace example.com with your domain.
This configuration sends incoming requests to the Blue application.
For HTTPS, configure TLS certificates and listen on port 443 as appropriate.
Why use Nginx?
Nginx separates incoming traffic from the application containers.
Instead of exposing application ports publicly, you can bind them to the loopback interface and allow Nginx to act as the public entry point.
This provides several advantages:
Centralized routing.
TLS termination.
Request forwarding.
Support for WebSocket connections.
Easier switching between application versions.
The ability to reload routing configuration without routinely stopping the Nginx service.
Important: Nginx does not automatically make a deployment zero-downtime. The new application must be ready before traffic is switched.
Step 5: Prepare the VPS
Install Docker and Nginx on your Linux VPS using the installation instructions for your operating system.
Create a directory for the deployment configuration:
sudo mkdir -p /opt/zero-downtime
sudo chown "$USER":"$USER" /opt/zero-downtimeStore your Nginx configuration in this directory:
/opt/zero-downtime/
├── app-blue.conf
├── app-green.conf
└── deploy.shCreate app-blue.conf:
upstream node_application {
server 127.0.0.1:3001;
keepalive 32;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://node_application;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}Create app-green.conf with the same server configuration, but change the upstream port to 3002.
For example:
upstream node_application {
server 127.0.0.1:3002;
keepalive 32;
}The remaining server configuration should be identical.
Install the initial Blue configuration into Nginx:
sudo cp /opt/zero-downtime/app-blue.conf \
/etc/nginx/conf.d/app.confMake sure the Nginx main configuration includes files from /etc/nginx/conf.d/.
Test the configuration:
sudo nginx -tApply it:
sudo systemctl reload nginxNginx performs a graceful reload when the configuration is valid. Existing workers can finish processing their requests while new workers begin handling incoming traffic.
Before continuing, ensure your initial Blue application is running on port 3001.
Step 6: Push Docker Images to a Container Registry
Your GitHub Actions workflow needs a place to publish the Docker image. In this example, we'll use Docker Hub.
Create a Docker Hub repository and configure these GitHub repository secrets:
Secret | Purpose |
|---|---|
| Docker Hub username |
| Docker Hub access token |
| VPS IP address or hostname |
| SSH deployment user |
| Private SSH key for deployment |
| Verified SSH host-key entry |
Use a dedicated deployment account with only the permissions required to deploy the application.
Do not commit SSH private keys, access tokens, or environment files to your Git repository.
Step 7: Create a GitHub Actions Workflow
Create this file:
.github/workflows/deploy.ymlAdd the following workflow:
name: Deploy Node.js Application
on:
push:
branches:
- main
permissions:
contents: read
concurrency:
group: production-deployment
cancel-in-progress: false
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push Docker image
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: |
${{ secrets.DOCKERHUB_USERNAME }}/zero-downtime-demo:${{ github.sha }}
- name: Configure SSH
env:
SSH_PRIVATE_KEY: ${{ secrets.VPS_SSH_KEY }}
SSH_KNOWN_HOSTS: ${{ secrets.VPS_KNOWN_HOSTS }}
run: |
install -m 700 -d ~/.ssh
printf '%s\n' "$SSH_PRIVATE_KEY" > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519
printf '%s\n' "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
chmod 600 ~/.ssh/known_hosts
- name: Deploy to VPS
env:
VPS_HOST: ${{ secrets.VPS_HOST }}
VPS_USER: ${{ secrets.VPS_USER }}
IMAGE: ${{ secrets.DOCKERHUB_USERNAME }}/zero-downtime-demo:${{ github.sha }}
run: |
ssh "$VPS_USER@$VPS_HOST" \
"bash /opt/zero-downtime/deploy.sh '$IMAGE'"This workflow builds an image for each commit and tags it with the commit SHA.
Using a unique image tag makes it easier to identify which version is running and to redeploy a previous version.
The deployment script receives the image tag and handles the actual blue-green switch.
For production use, pin third-party GitHub Actions to verified full commit SHAs and update those pins deliberately. Also configure the SSH host key using a trusted verification process rather than blindly accepting an unknown host.
Step 8: Implement the Blue-Green Deployment Script
Create /opt/zero-downtime/deploy.sh on your VPS.
This script will:
Identify the inactive application slot.
Pull the requested Docker image.
Start the new container on the inactive port.
Wait for the health check to pass.
Switch Nginx to the new slot.
Gracefully reload Nginx.
Keep the previous application available for a short period before stopping it.
Here's a simplified implementation:
#!/usr/bin/env bash
set -Eeuo pipefail
IMAGE="${1:?Usage: deploy.sh <image>}"
BASE_DIR="/opt/zero-downtime"
NGINX_CONF="/etc/nginx/conf.d/app.conf"
BLUE_PORT=3001
GREEN_PORT=3002
BLUE_CONF="$BASE_DIR/app-blue.conf"
GREEN_CONF="$BASE_DIR/app-green.conf"
BLUE_NAME="zero-downtime-blue"
GREEN_NAME="zero-downtime-green"
ACTIVE_SLOT=""
detect_active_slot() {
if [[ -f "$NGINX_CONF" ]] &&
grep -q "127.0.0.1:$BLUE_PORT" "$NGINX_CONF"; then
ACTIVE_SLOT="blue"
elif [[ -f "$NGINX_CONF" ]] &&
grep -q "127.0.0.1:$GREEN_PORT" "$NGINX_CONF"; then
ACTIVE_SLOT="green"
else
echo "Unable to determine active application slot."
exit 1
fi
}
health_check() {
local port="$1"
local attempts=30
for ((i = 1; i <= attempts; i++)); do
if curl --fail --silent \
"http://127.0.0.1:${port}/health" >/dev/null; then
echo "Application is healthy on port $port"
return 0
fi
sleep 2
done
echo "Health check failed on port $port"
return 1
}
detect_active_slot
if [[ "$ACTIVE_SLOT" == "blue" ]]; then
NEW_SLOT="green"
NEW_PORT="$GREEN_PORT"
NEW_NAME="$GREEN_NAME"
NEW_CONF="$GREEN_CONF"
OLD_NAME="$BLUE_NAME"
else
NEW_SLOT="blue"
NEW_PORT="$BLUE_PORT"
NEW_NAME="$BLUE_NAME"
NEW_CONF="$BLUE_CONF"
OLD_NAME="$GREEN_NAME"
fi
echo "Current active slot: $ACTIVE_SLOT"
echo "Deploying to slot: $NEW_SLOT"
echo "Image: $IMAGE"
docker pull "$IMAGE"
# Start the new version without replacing the active application.
docker rm -f "$NEW_NAME" >/dev/null 2>&1 || true
docker run -d \
--name "$NEW_NAME" \
--restart unless-stopped \
-e NODE_ENV=production \
-e APP_VERSION="$IMAGE" \
-p "127.0.0.1:${NEW_PORT}:3000" \
"$IMAGE"
# Do not switch traffic until the new version is healthy.
if ! health_check "$NEW_PORT"; then
docker logs "$NEW_NAME" || true
docker rm -f "$NEW_NAME" || true
echo "Deployment aborted. Existing application remains active."
exit 1
fi
# Save the current Nginx configuration for rollback.
sudo cp "$NGINX_CONF" "$BASE_DIR/app.conf.previous"
# Install the new routing configuration.
sudo cp "$NEW_CONF" "$NGINX_CONF"
# Validate before applying the change.
if ! sudo nginx -t; then
sudo cp "$BASE_DIR/app.conf.previous" "$NGINX_CONF"
echo "Invalid Nginx configuration. Previous configuration restored."
exit 1
fi
# Gracefully reload Nginx.
if ! sudo systemctl reload nginx; then
sudo cp "$BASE_DIR/app.conf.previous" "$NGINX_CONF"
sudo nginx -t && sudo systemctl reload nginx
echo "Nginx reload failed. Previous routing configuration restored."
exit 1
fi
echo "Traffic switched to $NEW_SLOT."
# Allow time for the previous version to drain.
sleep 10
# Stop the previous application only after the switch.
docker rm -f "$OLD_NAME" >/dev/null 2>&1 || true
echo "Deployment completed successfully."Make the script executable:
chmod +x /opt/zero-downtime/deploy.shImportant production considerations
This script illustrates the deployment flow, but it is not a complete production deployment controller.
Before using it in production:
Configure
sudopermissions for the deployment account and required commands.Protect deployments with a lock to prevent concurrent executions.
Ensure the initial Blue container and Nginx configuration are in sync.
Verify the new application through Nginx after switching traffic.
Improve rollback handling for failed reloads and failed post-deployment checks.
Replace fixed sleep periods with appropriate draining and verification logic.
Avoid stopping a previous container if another deployment has already changed the active slot.
Preserve old containers and image tags until rollback is no longer needed.
The sample script uses container names for simplicity. In a mature deployment system, store deployment state explicitly and use atomic configuration updates, robust error handling, and a reliable locking mechanism.
Also, the example maps each application container to a loopback port on the host. Both slots must use distinct host ports, and the new container must not reuse the port occupied by the active version.
Step 9: Test the Deployment
After configuring GitHub Actions, commit and push your code:
git add .
git commit -m "Add zero-downtime deployment workflow"
git push origin mainGitHub Actions should build the image, publish it to Docker Hub, and invoke the deployment script on your VPS.
Check which version is responding:
curl http://example.com/Example response:
{
"message": "Application is running",
"version": "your-image-tag"
}You can also inspect the running containers:
docker psCheck the deployment logs:
docker logs zero-downtime-greenThe exact container name depends on which slot is active.
Test the deployment while sending requests
Open a terminal and repeatedly send requests:
while true; do
curl --silent --output /dev/null \
--write-out '%{http_code}\n' \
http://example.com/
sleep 0.2
doneIn another terminal, deploy a new version.
If the deployment is configured correctly, requests should continue returning successful HTTP status codes during the switch.
For a stronger test, run a load-testing tool against the application while deploying. Monitor response times, connection errors, HTTP status codes, and application logs.
A successful test on one endpoint does not prove that every API route, WebSocket connection, or background job will remain uninterrupted.
Step 10: Handle Rollbacks
A new version may pass its initial health check but fail when real users interact with it.
For example, version 2.0 might contain a database query that fails under production data.
A reliable deployment strategy should make it possible to return traffic to the previous version.
The basic rollback procedure is:
Keep the previous application image available.
Keep the previous container running until the new version is verified.
Restore the previous Nginx configuration.
Validate the configuration with
nginx -t.Gracefully reload Nginx.
Confirm that the previous version is healthy.
For example, if Blue is the previous version:
sudo cp /opt/zero-downtime/app-blue.conf \
/etc/nginx/conf.d/app.conf
sudo nginx -t
sudo systemctl reload nginxThese commands restore Blue routing only if the Blue container is still running and healthy.
Do not remove the previous container immediately after switching traffic if you need a fast rollback window. Keep it available until the new version has passed the necessary checks.
For more advanced systems, automate rollback based on failed health checks, elevated error rates, or application-specific metrics.
Step 11: Understand Database Migrations
Application deployment is only one part of a production release. Database changes can also cause downtime or make rollback impossible.
Suppose version 1.0 expects a database field named fullName, while version 2.0 expects name.
If you rename the field immediately, the old application may stop working before the new version becomes active.
A safer approach is the expand-and-contract migration pattern.
Expand phase
Add the new database field without immediately removing the old one.
For example, introduce name while keeping fullName.
Compatibility phase
Deploy an application version that can read the old field and the new field. Where necessary, write both fields during the transition.
Migration phase
Backfill the new field for existing records and verify the results.
Contract phase
After all running application versions no longer depend on the old field, remove the obsolete field in a later release.
This approach helps maintain compatibility between application versions during deployment and rollback.
The exact migration process depends on your database, data volume, and consistency requirements.
Step 12: Production Best Practices
Zero-downtime deployments require more than switching ports. Consider these practices when preparing an application for production.
1. Use immutable Docker images
Build an image for each release and deploy it using a unique tag.
Avoid relying exclusively on the latest tag because it does not clearly identify the version being deployed.
2. Add meaningful health checks
A process can be running while the application is unable to serve requests.
Health checks should verify the application is ready to handle traffic. Depending on your architecture, readiness may require database connectivity or other critical dependencies.
Keep liveness checks separate from readiness checks when the distinction is useful.
3. Use graceful shutdown
Handle termination signals correctly and stop accepting new work before closing database connections and other resources.
For applications with long-running requests, use a suitable drain period rather than assuming every request finishes within a few seconds.
4. Monitor deployments
Track:
HTTP error rates.
Response latency.
Container restarts.
Health-check failures.
CPU and memory usage.
Application logs.
Database connection failures.
Monitoring helps identify problems that basic health checks might miss.
5. Protect secrets
Keep production secrets outside your Docker image and source repository.
Use GitHub Actions secrets for CI/CD credentials and an appropriate secret-management solution for runtime application credentials.
6. Avoid concurrent deployments
Two deployments running simultaneously can overwrite routing configuration or stop the wrong application container.
Use deployment locks, serialized workflows, and explicit active-slot tracking.
7. Consider WebSocket connections
Applications using Socket.IO or WebSockets need special attention.
Nginx must forward the required upgrade headers, and the application must handle connections that remain open during a deployment.
Long-lived connections may need to reconnect to the new application. Shared session state, Redis adapters, and graceful connection draining may be necessary for more complex systems.
8. Plan for infrastructure failures
Blue-green deployment on a single VPS protects against many release-related interruptions, but it does not protect against the VPS itself failing.
For higher availability, consider multiple servers, a load balancer, health-based routing, automated recovery, and geographically appropriate backups.
Blue-Green Deployment vs. Rolling Deployment
Both blue-green and rolling deployments can reduce downtime, but they work differently.
Feature | Blue-Green Deployment | Rolling Deployment |
|---|---|---|
Deployment approach | Runs old and new environments side by side | Replaces instances gradually |
Traffic switching | Switches traffic to the new environment | Moves capacity progressively |
Rollback | Often straightforward if the old environment remains available | Depends on how many instances have been updated |
Infrastructure requirements | Needs capacity for both environments | Usually needs enough capacity to replace instances safely |
Operational complexity | Requires environment and routing management | Requires orchestration and readiness management |
Suitable for | Small VPS setups and controlled releases | Larger services with multiple application instances |
For a small Node.js application on a VPS, blue-green deployment is often a practical starting point. For larger systems, rolling deployments managed by an orchestrator may provide more flexibility.
Common Mistakes to Avoid
Stopping the old container too early: The new version should be healthy and receiving traffic before the previous version is removed.
Skipping health checks: A running container does not necessarily mean the application is ready.
Using incompatible database migrations: Database changes must support the versions that may run during the transition.
Reloading invalid Nginx configuration: Always run nginx -t before applying routing changes.
Assuming rollback reverses database changes: Restoring an older application image does not automatically reverse a database migration.
Ignoring persistent connections: WebSockets and long-running requests may require a separate draining strategy.
Assuming a single VPS provides high availability: Blue-green deployment reduces release-related downtime but cannot eliminate server-level failures.
Frequently Asked Questions
1. Is zero-downtime deployment possible with Docker?
Yes. Docker supports running multiple containers simultaneously, making it possible to start a new application version while the old version continues serving traffic. A reverse proxy or load balancer can then direct requests to the new version.
2. Why is Nginx useful for zero-downtime deployments?
Nginx acts as a reverse proxy between clients and application containers. It can route requests to different application ports and gracefully reload its configuration, allowing traffic to switch without routinely stopping the proxy service.
3. Can GitHub Actions automate the entire deployment?
Yes. GitHub Actions can run tests, build Docker images, publish them to a container registry, connect securely to a server, and trigger a deployment script. The server-side deployment logic is responsible for health checks and traffic switching.
4. What happens if the new container fails its health check?
The deployment should stop before switching traffic. The currently active application continues serving requests, while the failed new container is investigated or removed.
5. Does zero-downtime deployment require Kubernetes?
No. A small application can implement blue-green deployment using Docker, Nginx, and a deployment script on a VPS. Kubernetes and other orchestration platforms become useful as application complexity and infrastructure requirements grow.
6. Is blue-green deployment the same as rolling deployment?
No. Blue-green deployment maintains two environments and switches traffic between them. Rolling deployment updates application instances progressively while maintaining sufficient capacity to serve requests.
7. Can a deployment be zero-downtime if the database schema changes?
It can be, provided the migration is designed for compatibility between the old and new application versions. Expand-and-contract migrations are a common approach, but the correct strategy depends on the database and application.
Conclusion
Zero-downtime deployments help developers release application updates without routinely interrupting users.
By combining Docker, GitHub Actions, and Nginx, you can automate the deployment process, run a new application version alongside the existing one, verify its health, and switch traffic only when it is ready.
The blue-green strategy demonstrated in this guide provides a useful foundation for Node.js and MERN stack applications running on a VPS.
For production deployments, strengthen the workflow with automated rollback, deployment locking, monitoring, secure credentials, graceful shutdown, and backward-compatible database migrations.
The main principle is simple: prepare the new version first, verify that it works, and only then switch production traffic.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


