NixOS Configuration Patterns
The NixOS Module System
# Basic structure of a NixOS module
{ config, pkgs, lib, ... }:
with lib;
{
# Module options (schema)
options.services.myservice = {
enable = mkEnableOption "myservice";
port = mkOption {
type = types.port;
default = 8080;
description = "Port to listen on";
};
logLevel = mkOption {
type = types.enum [ "debug" "info" "warn" "error" ];
default = "info";
description = "Logging verbosity level";
};
};
# Module implementation
config = mkIf config.services.myservice.enable {
systemd.services.myservice = {
description = "My Custom Service";
wantedBy = [ "multi-user.target" ];
serviceConfig = {
ExecStart = "${pkgs.myservice}/bin/myservice --port ${toString config.services.myservice.port} --log-level ${config.services.myservice.logLevel}";
Restart = "always";
User = "myservice";
};
};
# Create the system user
users.users.myservice = {
isSystemUser = true;
createHome = true;
home = "/var/lib/myservice";
group = "myservice";
};
users.groups.myservice = {};
# Ensure data directory exists
systemd.tmpfiles.rules = [
"d /var/lib/myservice 0750 myservice myservice -"
];
};
}System Architecture Patterns
Layered System Configuration
Multi-Environment Configuration
Service Configuration Patterns
Service Factory Pattern
Consistent Database Services
Security Patterns
Defense in Depth Configuration
Networking Patterns
Multi-Environment Network Configuration
Storage and Filesystem Patterns
Resilient Storage Configuration
Deployment and Upgrade Patterns
Atomic Upgrades and Rollbacks
Infrastructure as Code Integration
Terraform Integration
Monitoring and Observability Patterns
Comprehensive System Monitoring
Conclusion
Further Resources
Last updated