Simple Blue Green deployment with Multipass

Motivation

I follow Pieter Levels and he uses (and inspires others to use) a simple tech stack and process, and codes directly on the production VPS. That saves him tons of money (no cloud, k8s, etc) and makes fixing bugs in production very simple.

At the time of this post the tools he uses are:

That works well for an indie dev and with interpreted languages.
For compiled languages, though, things get a bit trickier:

That got me thinking about how I could (hypothetically) use this lean approach for Go.
For that reason I created this post. It tries to adapt levelsio's way of working to a compiled server like Go.

With this post I am not inviting people to use this approach in production systems. We need to consider all the tradeoffs of going fully hacker, fully corporate, or something in between.
I am not responsible for any issues caused in production systems due to following this post.

What are we going to do

In this post we will create a simple blue-green deployment for our Go app.

Block 1: Configure the VM with nginx and the simple golang server

Block 2: Configure blue green deployment

I assume knowledge of Go and HTTP servers and basic knowledge about nginx (at least that it exists and what it does).

Let's start!

Block 1: Configure the VM with nginx and the simple golang server

http://multipass/homeHome Page ubuntu@multipass nginx:80 app:8081

Creating our simple Go server

Let's first initialize our Go project with go mod init bluegreen-demo

The official way to initialize a Go module is using a git repo, but for our use case we are using this simple name.
Let's create our server:

cmd/
    main.go <-- this file

We will create a http server with a healthcheck that will return a json and the status 200.
We can pass the port it has to listen to via cli args.

package main

import (
	"encoding/json"
	"flag"
	"net/http"
)

func writeJsonResponse(w http.ResponseWriter, data map[string]string) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(data)
}

func main() {
	var port = flag.String("port", "", "Port to listen on")
	flag.Parse()

	if *port == "" {
		panic("port is required")
	}

	http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
		writeJsonResponse(w, map[string]string{"message": "ok"})
	})

	http.ListenAndServe(":"+*port, nil)
}

We can run a quick test:

go build -o bluegreendemo cmd/main.go
./bluegreendemo --port 8080 &
sleep 1
curl -s http://localhost:8080/healthz | jq
pkill -f "./bluegreendemo --port 8080"

You should see the health response:

{
  "message": "ok"
}

Create a local VM with multipass

We will create a VM in our computer using multipass following the official docs.

Our VM locally will have the following specs:

Feel free to tweak your numbers.

For example, for macOS with Homebrew you can just run:

brew install multipass
multipass launch 24.04 --name bluegreen-demo --cpus 2 --memory 4G --disk 15G
multipass list

We should see that the machine is running:

Name                    State             IPv4             Image
bluegreen-demo          Running           192.168.64.8     Ubuntu 24.04 LTS

Deploy and start the application in the VM

To handle our deployment process cleanly, we'll create three specialized scripts:

cmd/
    main.go
scripts/
    prepare.sh   # Handles building and file transfers
    apply.sh     # Manages deployment in the VM
    ci.sh        # Orchestrates the whole process
go.mod

Make the scripts executable:

chmod +x scripts/prepare.sh scripts/apply.sh scripts/ci.sh

Let's implement each script:

prepare.sh - Building and File Transfers

This script handles the build process and transferring files to the VM:

#! /bin/bash

# Cross-compile for Linux ARM64
GOOS=linux GOARCH=arm64 go build -o bluegreendemo cmd/main.go

# Transfer files to the VM
multipass transfer ./bluegreendemo bluegreen-demo:bluegreendemo
multipass transfer ./scripts/apply.sh bluegreen-demo:apply.sh

apply.sh - VM-side Deployment

This script runs inside the VM and handles the application deployment:

#! /bin/bash

# Prepare app directory
sudo mkdir -p /app/
sudo chown ubuntu:ubuntu /app/

# Deploy application
mv bluegreendemo /app/app
chmod +x /app/app

# Start the application
/app/app --port 8081 &

ci.sh - Orchestrating the Process

This script coordinates the whole deployment:

#! /bin/bash

echo "Preparing deployment..."
./scripts/prepare.sh

echo "Deploying new version..."
multipass exec bluegreen-demo -- ./apply.sh

# Verify deployment
VM_IP=$(multipass info bluegreen-demo | grep IPv4 | awk '{print $2}')
curl -s http://$VM_IP:8081/healthz | jq

Run the deployment:

./scripts/ci.sh

If you see a JSON response with {"message": "ok"}, congratulations! Your app is running.

Install nginx

We need to install and configure nginx in our VM:

For that we will open a shell in the VM using multipass shell bluegreen-demo and run the following set of commands:

sudo apt update
sudo apt install nginx -y
nginx -v
sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl status nginx

At the end of the script you should see something like:

Sep 13 10:26:14 bluegreen-demo systemd[1]: Starting nginx.service - A high performance web server and a reverse proxy server...
Sep 13 10:26:14 bluegreen-demo systemd[1]: Started nginx.service - A high performance web server and a reverse proxy server.

Configure nginx to serve our application

We will configure nginx to serve our application in port 80 (default for http). For that we will create a minimum nginx.conf file to listen to port 80 and forward the requests to our app in port 8081.

cmd/
    main.go
nginx/
    nginx.conf <-- this file
scripts/
    apply.sh
    ci.sh
    prepare.sh
go.mod

These are the contents:

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;

    server {
        listen 80;
        server_name _;

        location / {
            proxy_pass http://localhost:8081;
        }
    }
}

We will need to update our scripts to handle the nginx configuration:

  1. Add nginx.conf transfer to prepare.sh (creating the target folder in the VM first):
multipass exec bluegreen-demo -- mkdir -p nginx
multipass transfer ./nginx/nginx.conf bluegreen-demo:nginx/nginx.conf
  1. Add nginx configuration to apply.sh:
sudo mv nginx/nginx.conf /etc/nginx/nginx.conf
sudo nginx -s reload

Let's try it out by running:

./scripts/ci.sh

Now we should be able to access our app using the port 80:

VM_IP=$(multipass info bluegreen-demo | grep IPv4 | awk '{print $2}')

curl -s http://$VM_IP/healthz | jq

We have nginx serving our app.

Block 2: Configure blue green deployment

Let's implement a blue-green deployment strategy that allows us to deploy new versions without downtime. The idea is simple:

Here's how it works:

http://multipass/homeBlue ubuntu@multipass nginx:80 blue:8081 green:8082

And after deploying and switching:

http://multipass/homeGreen ubuntu@multipass nginx:80 blue:8081 green:8082

Adding Color Support to Our Server

First, let's enhance our Go server to identify which version (blue or green) it is:

package main

import (
	"encoding/json"
	"flag"
	"net/http"
)

func writeJsonResponse(w http.ResponseWriter, data map[string]string) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(data)
}

func main() {
	var port = flag.String("port", "", "Port to listen on")

    // NEW: Get "color" as arg when the server starts
	var color = flag.String("color", "", "Color value to return in responses")
	flag.Parse()

	if *port == "" || *color == "" {
		panic("port and color are required")
	}

	http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
		writeJsonResponse(w, map[string]string{"message": "ok"})
	})

    // NEW: Return the "color" in the status endpoint
	http.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
		writeJsonResponse(w, map[string]string{
			"color": *color,
		})
	})

	http.ListenAndServe(":"+*port, nil)
}

Updating the Deployment Scripts for Blue-Green

Now that we've added color support to our server, we need to update our deployment scripts so that each deployment goes to the color that is not receiving traffic.

prepare.sh does not change. apply.sh is where the logic lives:

Updates to apply.sh

#! /bin/bash

# Get current active color (empty on the very first deployment)
CURRENT_COLOR=$(curl -s http://localhost/status | jq -r .color 2>/dev/null)

# Determine next deployment color
if [ "$CURRENT_COLOR" = "blue" ]; then
    NEXT_COLOR="green"
    NEXT_PORT="8082"
else
    NEXT_COLOR="blue"
    NEXT_PORT="8081"
fi

echo "Deploying $NEXT_COLOR on port $NEXT_PORT"

# Prepare deployment
sudo mkdir -p /app/
sudo chown ubuntu:ubuntu /app/
pkill -f /app/$NEXT_COLOR || true

# Deploy new version
mv bluegreendemo /app/$NEXT_COLOR
chmod +x /app/$NEXT_COLOR
/app/$NEXT_COLOR --port $NEXT_PORT --color $NEXT_COLOR &

# Wait until the new instance is healthy (10 seconds max)
for i in $(seq 1 10); do
    curl -sf http://localhost:$NEXT_PORT/healthz > /dev/null && break
    sleep 1
done

# Verify deployment
if curl -s http://localhost:$NEXT_PORT/status | grep -q "$NEXT_COLOR"; then
    echo "$NEXT_COLOR is up on port $NEXT_PORT"
else
    echo "Deployment failed - new version not responding"
    exit 1
fi

Instead of sleeping for a fixed amount of time, the script polls the health endpoint and continues as soon as the new instance answers.
The script needs jq inside the VM. If it is not there yet: multipass exec bluegreen-demo -- sudo apt install jq -y.

Updates to ci.sh

ci.sh now reports which color is being served through nginx:

#! /bin/bash

echo "Preparing deployment..."
./scripts/prepare.sh

echo "Deploying new version..."
multipass exec bluegreen-demo -- ./apply.sh

# Check which version is being served
VM_IP=$(multipass info bluegreen-demo | grep IPv4 | awk '{print $2}')
echo "Current version:"
curl -s http://$VM_IP/status | jq

The instance we started in Block 1 (/app/app) is still listening on port 8081 and it knows nothing about colors, so we stop it once and then deploy twice:

multipass exec bluegreen-demo -- pkill -f /app/app

./scripts/ci.sh   # deploys blue on port 8081
./scripts/ci.sh   # deploys green on port 8082

If we check from the host:

VM_IP=$(multipass info bluegreen-demo | grep IPv4 | awk '{print $2}')

echo "Checking green"
curl -s http://$VM_IP:8082/status | jq -r .color

echo "Checking default"
curl -s http://$VM_IP/status | jq -r .color

We should see:

Checking green
green
Checking default
blue

Green is running properly but nginx still points to blue (we hardcoded port 8081, remember?)

Configuring Nginx for Zero-Downtime Switching

The final piece is making nginx switch between versions. We will use nginx's upstream feature and a symbolic link that points to the configuration of the active color.

1. Setting up the Configuration Structure

We'll have three configuration files:

nginx/
    nginx.conf         # Main configuration with routing logic
    blue.conf          # Blue instance configuration (port 8081)
    green.conf         # Green instance configuration (port 8082)

2. Creating Instance-Specific Configs

Each color gets its own configuration that defines where its instance runs:

blue.conf:

upstream app_backend {
    server 127.0.0.1:8081;
}

green.conf:

upstream app_backend {
    server 127.0.0.1:8082;
}

3. Setting up the Main Configuration

Update nginx.conf to use the dynamic backend:

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    include /etc/nginx/upstream.conf;  # Dynamic backend selection

    server {
        listen 80;
        server_name _;

        location / {
            proxy_pass http://app_backend;  # Routes to active instance
        }
    }
}

4. Implementing the Switch Mechanism

  1. Transfer the two new files in prepare.sh, next to nginx.conf:

    multipass transfer ./nginx/blue.conf bluegreen-demo:nginx/blue.conf
    multipass transfer ./nginx/green.conf bluegreen-demo:nginx/green.conf
    
  2. In apply.sh, switch traffic once the new version is verified:

    # Verify deployment
    if curl -s http://localhost:$NEXT_PORT/status | grep -q "$NEXT_COLOR"; then
        # Switch traffic
        sudo cp nginx/*.conf /etc/nginx/
        sudo ln -sf /etc/nginx/$NEXT_COLOR.conf /etc/nginx/upstream.conf
        sudo nginx -s reload
        echo "Switched to $NEXT_COLOR"
    else
        echo "Deployment failed - new version not responding"
        exit 1
    fi
    

This setup gives us two key benefits:

If we run our ci again and again we should see the color alternating between green and blue:

VM_IP=$(multipass info bluegreen-demo | grep IPv4 | awk '{print $2}')

./scripts/ci.sh
curl -s http://$VM_IP/status | jq -r .color

Conclusion

We've created a simple blue-green deployment system that:

There are things this setup does not cover: the instances do not survive a reboot of the VM (they would need a systemd unit), and database migrations need their own strategy since both versions share the same data.

This approach shows how we can adapt modern deployment practices to a lean, cost-effective setup inspired by levelsio's philosophy. While this example uses Go, the same principles can work with any compiled language.

Next Steps

Some ways of taking this solution further: