When I upgrade NixOS of for my mini-server with:

$ sudo nixos-rebuild switch --upgrade

It’ll download tons of packages from http://nixos-cache.example.com/ which is unbearable slow. Then I tried to build some of them instead of download the prebuild version1:

sudo nixos-rebuild switch --option substitute false

However, the SSD of the mini-server have only 5G. The upgrade failed when building gcc.

I have a server with socks5 proxy, which can access the cache.nixos.org faster. It can be used as cache proxy to make sure the download reliable.

Here is the whole steps.

Create Cache Proxy with Nginx

worker_processes  1;
master_process off;
error_log logs/error.log;

events {
    worker_connections 1024;
}

http {
    map $status $cache_header {
        200     "public";
        302     "public";
        default "no-cache";
    }

    server {
        listen 6699;

        resolver 8.8.8.8;
        set $upstream_endpoint http://cache.nixos.org;

        location / {
            error_page 404 = @fallback;
        }

        location @fallback {
          proxy_pass $upstream_endpoint;
          # proxy_cache cachecache;
          proxy_cache_valid  200 302  60m;
          expires max;
          add_header Cache-Control $cache_header always;
        }

        location ~ ^/nix-cache-info {
           proxy_store        on;
           proxy_store_access user:rw group:rw all:r;
           proxy_temp_path    /data/nginx/nix-cache-info/temp;
           root               /data/nginx/nix-cache-info/store;

           proxy_set_header Host "cache.nixos.org";
           proxy_pass https://cache.nixos.org;
         }

         location ~^/nar/.+$ {
           proxy_store        on;
           proxy_store_access user:rw group:rw all:r;
           proxy_temp_path    /data/nginx/nar/temp;
           root               /data/nginx/nar/store;

           proxy_set_header Host "cache.nixos.org";
           proxy_pass https://cache.nixos.org;
         }
    }

Upgrade through cache proxy

sudo nixos-rebuild switch --option binary-caches "http://example.com:6699"