Using systemd to switch nginx configurations based on number of CPUs

| geek

I set up a BigBlueButton web conferencing server so that people can use it for Emacs meetups. To keep costs down, I want to resize it to 1 GB RAM 1 vCPU most of the time, and then resize it to 8 GB RAM 4 vCPU when there's a meetup. When it's at a proper size (4 CPUs), the Nginx web server should proxy the Greenlight web interface for BigBlueButton. In between meetups, I want to display a backup page to let people know they've got the right URL but that it's not up yet.

First, I need a shell script that returns the name of the configuration file to use. This is /usr/local/bin/nginx-cpu-config.sh:

#!/bin/bash
cpu_count=$(nproc)
if [ "$cpu_count" -ge 4 ]; then
    echo "/etc/nginx/nginx.conf"
else
    echo "/etc/nginx/backup-nginx.conf"
fi

Next, I need to copy /etc/nginx/nginx.conf to /etc/nginx/backup-nginx.conf. Instead of include /etc/nginx/sites-available/*;, I'll use include /etc/nginx/sites-backup/*;. Then I need to set up a copy of the /etc/nginx/sites-available/bigbluebutton in /etc/nginx/sites-backup/bigbluebutton. I changed the try_files so that it tries the backup file.

  # BigBlueButton landing page.
  location / {
    root   /var/www/bigbluebutton-default/assets;
    try_files $uri /backup/index.html @bbb-fe;
  }

I set up a /var/www/bigbluebutton/assets/backup/index.html with the message that I wanted to display between meetups.

I removed the /etc/systemd/system/haproxy.service.d/require-cpu.conf I had previously set up, so it would start even if downscaled to a single CPU. Then I created a /etc/systemd/system/nginx.service.d/based-on-cpus.conf with the following contents:

[Service]
ExecStartPre=
ExecStartPre=/bin/bash -c '/usr/sbin/nginx -t -c $(/usr/local/bin/nginx-cpu-config.sh)'
ExecStart=
ExecStart=/bin/bash -c '/usr/sbin/nginx -c $(/usr/local/bin/nginx-cpu-config.sh)'
ExecReload=
ExecReload=/bin/bash -c '/usr/sbin/nginx -s reload -c $(/usr/local/bin/nginx-cpu-config.sh)'

Then I ran systemctl daemon-reload and used service nginx restart to test.

Seems to be working. We'll see!

View org source for this post
You can comment with Disqus (JS required) or you can e-mail me at sacha@sachachua.com.