← See all notes

Table of Contents

Zero downtime deployments with Nginx

Relevant blog post explaining mostly the same: https://kaiwern.com/posts/2021/05/15/blue-green-deployment-with-nginx-for-elixir-phoenix-release/

Preparation 🔗

Ensure your environment is set up with Nginx and that your application can be started in such a way that it listens on a specific port you can control. This might involve configuring your application to read a port number from an environment variable or a configuration file.

Deployment Script 🔗

Create a deployment script that performs the following steps:

upstream myapp {
    server 127.0.0.1:<green_port>;
}

Automation with CI/CD Tools 🔗

To fully automate the process, you can integrate the deployment script into a CI/CD pipeline using tools like Jenkins, GitLab CI, GitHub Actions, or CircleCI. Here’s a simplified workflow:

Script Example 🔗

Here’s a very simplified version of what the script part could look like. Note that actual implementation details will depend on your specific application setup:

#!/bin/bash

# Configuration
GREEN_PORT=8081
BLUE_PORT=8080
NGINX_CONFIG="/etc/nginx/sites-available/myapp"
APP_DIRECTORY="/var/www/myapp"


# Deploy new version (Green)
# This would include pulling the new code, compiling it if necessary, and any other setup required
cp -R "${APP_DIRECTORY}_blue" "${APP_DIRECTORY}_green"
# Assume start_app.sh takes a port number as an argument
bash start_app.sh $GREEN_PORT "${APP_DIRECTORY}_green"


# Health check
if ! curl -f <http://localhost>:$GREEN_PORT/health; then
  echo "Health check failed"
  exit 1
fi


# Update Nginx to point to Green
sed -i "s/server 127.0.0.1:$BLUE_PORT;/server 127.0.0.1:$GREEN_PORT;/" $NGINX_CONFIG


# Reload Nginx
nginx -s reload


# Additional steps might include monitoring and eventually cleaning up the old deployment

Script considerations 🔗