better cleaner containers

This commit is contained in:
ari committed 2026-06-28 15:55:16 -04:00
1 parent 3aa7119bed
commit d9b984db7f
13 files changed
+550 -320

No files matched your search

+9
View File
@@ -13,6 +13,7 @@ let
libretranslate = 5000;
signal = 8080;
hermes = 8642;
hermesDashboard = 9119;
};
openPorts = [
ports.ollama
@@ -22,6 +23,8 @@ let
ports.wyoming
ports.comfyui
ports.libretranslate
ports.hermes
ports.hermesDashboard
];
in
{
@@ -186,6 +189,12 @@ in
PGID = "100"; # GID of the 'users' group in NixOS
};
extraConfig.shm_size = "1g";
files = {
"/opt/data/config.yaml" = ''
terminal:
backend: docker
'';
};
};
};
# Signal CLI
+10 -1
View File
@@ -9,7 +9,14 @@ containers/
├── default.nix # Shared runtime options (runtime, enableOnBoot, registries, metrics)
├── docker.nix # Applied when runtime == "docker"
├── podman.nix # Applied when runtime == "podman" (dockerCompat + socket)
├── container-services.nix # Compose-style groups → rendered compose.yml + systemd oneshot
├── container-services/ # Compose-style service groups (modular implementation)
│ ├── default.nix
│ ├── options.nix
│ ├── lib.nix
│ ├── compose.nix
│ ├── files.nix
│ ├── systemd.nix
│ └── ABOUTME.md
└── user-guide.md # Full usage docs for container-services
```
@@ -60,6 +67,8 @@ skyg.nixos.common.container-services.my-stack = {
See [user-guide.md](./user-guide.md) for the full option reference and day-2 ops.
For module implementation details, see [container-services/ABOUTME.md](./container-services/ABOUTME.md).
## Conventions
- Always select the runtime via `skyg.nixos.common.containers.runtime`; do not enable both
@@ -1,318 +0,0 @@
{ config, pkgs, lib, ... }:
let
containersCfg = config.skyg.nixos.common.containers;
cfg = config.skyg.nixos.common.container-services;
isDocker = containersCfg.runtime == "docker";
composeBin =
if isDocker
then "${pkgs.docker-compose}/bin/docker-compose"
else "${pkgs.podman-compose}/bin/podman-compose";
runtimeService =
if isDocker then "docker.service" else "podman.service";
# ── Compose document builder ─────────────────────────────────────────────
# Build one compose service entry from a service config.
# groupName is threaded in so the default network reference is correct.
mkComposeService = groupName: _svcName: svcCfg:
{
image = svcCfg.image;
restart = svcCfg.restart;
networks =
if svcCfg.networks == [ ]
then [ groupName ]
else svcCfg.networks;
}
// lib.optionalAttrs (svcCfg.command != [ ]) {
command = svcCfg.command;
}
// lib.optionalAttrs (svcCfg.ports != [ ]) {
ports = svcCfg.ports;
}
// lib.optionalAttrs (svcCfg.volumes != [ ]) {
volumes = svcCfg.volumes;
}
// lib.optionalAttrs (svcCfg.environment != { }) {
environment = svcCfg.environment;
}
// lib.optionalAttrs (svcCfg.environmentFiles != [ ]) {
env_file = map builtins.toString svcCfg.environmentFiles;
}
// lib.optionalAttrs (svcCfg.dependsOn != [ ]) {
depends_on = svcCfg.dependsOn;
}
// svcCfg.extraConfig;
# Build the full compose document attrset for a group.
mkComposeAttrs = groupName: grpCfg:
let
networks =
if grpCfg.networks == { }
then { "${groupName}" = { driver = "bridge"; }; }
else grpCfg.networks;
in
{
services = lib.mapAttrs (mkComposeService groupName) grpCfg.services;
networks = networks;
}
// lib.optionalAttrs (grpCfg.volumes != [ ]) {
volumes = lib.genAttrs grpCfg.volumes (_: { });
}
// grpCfg.extraConfig;
# Render compose.yml to the Nix store.
mkComposeFile = groupName: grpCfg:
(pkgs.formats.yaml { }).generate "compose.yml"
(mkComposeAttrs groupName grpCfg);
# ── Systemd service builder ──────────────────────────────────────────────
# Collect all env files from all services in a group.
getAllEnvFiles = grpCfg:
lib.concatLists
(lib.attrValues
(lib.mapAttrs (_: svcCfg: svcCfg.environmentFiles) grpCfg.services));
mkSystemdService = groupName: grpCfg:
let
composeFile = mkComposeFile groupName grpCfg;
stateDir = grpCfg.stateDir;
in
{
description = "Container service group '${groupName}'";
wantedBy = [ "multi-user.target" ];
# agenix.service decrypts secrets before we try to read env_file paths
after = [ runtimeService "network-online.target" "agenix.service" ];
requires = [ runtimeService ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
TimeoutStopSec = grpCfg.timeoutStopSec;
# Stage the store-rendered compose.yml into a stable, readable location
ExecStartPre = "${pkgs.coreutils}/bin/cp ${composeFile} ${stateDir}/compose.yml";
ExecStart = "${composeBin} -p ${groupName} -f ${stateDir}/compose.yml up -d --remove-orphans";
ExecStop = "${composeBin} -p ${groupName} -f ${stateDir}/compose.yml down";
};
};
# Create a path unit that triggers a restart when env files change.
mkPathUnit = groupName: envFiles:
lib.optionalAttrs (envFiles != [ ]) {
"container-services-${groupName}-env-reload" = {
description = "Watch env files for container service group '${groupName}'";
pathConfig = {
PathChanged = map builtins.toString envFiles;
Unit = "container-services-${groupName}-env-reload.service";
};
wantedBy = [ "multi-user.target" ];
};
};
# Service that restarts the compose stack when env files change.
mkEnvReloadService = groupName:
{
"container-services-${groupName}-env-reload" = {
description = "Restart container service group '${groupName}' on env file changes";
serviceConfig = {
Type = "oneshot";
# Restart the compose stack
ExecStart = "${pkgs.systemd}/bin/systemctl restart container-services-${groupName}.service";
};
};
};
enabledGroups = lib.filterAttrs (_: g: g.enable) cfg;
in
{
# ── Option declarations ──────────────────────────────────────────────────
options.skyg.nixos.common.container-services = lib.mkOption {
description = ''
Compose-style container service groups.
Each group is rendered to a compose.yml in the Nix store, staged into
its stateDir on activation, and managed by a single systemd oneshot unit:
container-services-<group>.service
See modules/nixos/common/containers/user-guide.md for full documentation.
'';
default = { };
type = lib.types.attrsOf (lib.types.submodule ({ name, ... }: {
options = {
enable = lib.mkEnableOption "this container service group" // { default = true; };
stateDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/container-services/${name}";
description = "Directory where the staged compose.yml lives at runtime.";
};
timeoutStopSec = lib.mkOption {
type = lib.types.int;
default = 120;
description = "Seconds to wait for 'compose down' before forcibly killing containers.";
};
services = lib.mkOption {
description = "Container services in this group (maps to compose services: block).";
default = { };
type = lib.types.attrsOf (lib.types.submodule {
options = {
image = lib.mkOption {
type = lib.types.str;
description = "Container image (registry/name:tag).";
};
command = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Entrypoint command override (compose command:).";
};
ports = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [ "8642:8642" ];
description = "Port mappings in HOST:CONTAINER format.";
};
volumes = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [ "/var/lib/hermes:/opt/data" ];
description = "Volume mounts in src:dst[:opts] format.";
};
environment = lib.mkOption {
type = lib.types.attrsOf lib.types.str;
default = { };
description = "Environment variables as key/value pairs.";
};
environmentFiles = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = ''
Paths to env files loaded by compose at runtime.
Accepts runtime paths such as agenix secret paths
(e.g. config.age.secrets.my-secret.path).
Changes to these files will trigger an automatic restart.
'';
};
dependsOn = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Sibling service names that must start first (compose depends_on:).";
};
restart = lib.mkOption {
type = lib.types.str;
default = "unless-stopped";
description = "Compose restart policy.";
};
networks = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = ''
Networks to join. Empty list = attach to the group's
auto-created bridge network (named after the group).
'';
};
extraConfig = lib.mkOption {
type = lib.types.attrsOf lib.types.anything;
default = { };
description = ''
Free-form attrset merged directly into the compose service
block. Use this for keys not modelled above:
shm_size, cap_add, devices, healthcheck, etc.
'';
};
};
});
};
volumes = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Named volumes declared at the top level of the compose document.";
};
networks = lib.mkOption {
type = lib.types.attrsOf lib.types.anything;
default = { };
description = ''
Network definitions for the top-level compose networks: block.
Empty = auto-create a bridge network named after the group.
'';
};
extraConfig = lib.mkOption {
type = lib.types.attrsOf lib.types.anything;
default = { };
description = "Free-form attrset merged into the top-level compose document.";
};
};
}));
};
# ── Configuration ────────────────────────────────────────────────────────
config = {
assertions = lib.optionals (enabledGroups != { }) [
{
assertion = config.virtualisation.docker.enable or false
|| config.virtualisation.podman.enable or false;
message = ''
skyg.nixos.common.container-services: at least one container runtime
must be enabled. Set skyg.nixos.common.containers.runtime (or enable
virtualisation.docker / virtualisation.podman directly).
'';
}
];
# Create each group's stateDir via tmpfiles so the cp in ExecStartPre succeeds.
systemd.tmpfiles.rules =
lib.mapAttrsToList
(_: grpCfg: "d ${grpCfg.stateDir} 0750 root root -")
enabledGroups;
# One oneshot unit per group — manages the whole compose stack.
systemd.services =
lib.mapAttrs'
(groupName: grpCfg:
lib.nameValuePair
"container-services-${groupName}"
(mkSystemdService groupName grpCfg))
enabledGroups
// lib.foldAttrs lib.recursiveUpdate { } (
lib.mapAttrsToList
(groupName: grpCfg:
mkEnvReloadService groupName)
(lib.filterAttrs
(_: grpCfg: getAllEnvFiles grpCfg != [ ])
enabledGroups)
);
# Path units that watch env files and trigger restarts.
systemd.paths =
lib.foldAttrs lib.recursiveUpdate { } (
lib.mapAttrsToList
(groupName: grpCfg:
mkPathUnit groupName (getAllEnvFiles grpCfg))
enabledGroups
);
};
}
@@ -0,0 +1,39 @@
# container-services/
Custom compose-style container service groups for systemd.
## Files
| File | Purpose |
|------|---------|
| `default.nix` | Main module entry point; imports options and wires everything |
| `options.nix` | All `skyg.nixos.common.container-services.*` option declarations |
| `lib.nix` | Shared helpers (runtime dispatch, path sanitization, env file collection) |
| `compose.nix` | YAML composition (mkComposeService, mkComposeAttrs, mkComposeFile) |
| `files.nix` | File mounting logic (getAllFiles, mkFileVolumesForService, mkFilesService) |
| `systemd.nix` | Systemd unit builders (mkSystemdService, mkPathUnit, mkEnvReloadService) |
## How it works
1. User declares a group under `skyg.nixos.common.container-services.<group>`
2. `options.nix` validates the structure
3. `lib.nix` provides runtime dispatch (docker vs podman)
4. `compose.nix` renders a YAML compose file with all services
5. `files.nix` collects custom files, generates write commands, and builds file volume mounts
6. `systemd.nix` builds oneshot units to manage the stack
7. `default.nix` wires tmpfiles, services, and paths together
## Adding a new feature
If adding a new per-service option:
1. Add it to the submodule in `options.nix`
2. Update the builder(s) in `compose.nix`, `files.nix`, or `systemd.nix` as needed
3. Update `user-guide.md` with examples
## Architecture
- Each group gets **one** systemd unit (`container-services-<group>.service`) that manages the whole stack
- Custom files are collected and written by a separate unit (`container-services-<group>-files.service`)
- Env file changes trigger a path unit that restarts the stack (`container-services-<group>-env-reload.*`)
- Compose files are rendered to the store and staged to `/var/lib/container-services/<group>/compose.yml`
@@ -0,0 +1,60 @@
{ lib }:
rec {
# Build one compose service entry from a service config.
# Includes both user volumes and file-mounted volumes.
mkComposeService = groupName: _svcName: svcCfg: fileVolumes:
{
image = svcCfg.image;
restart = svcCfg.restart;
networks =
if svcCfg.networks == [ ]
then [ groupName ]
else svcCfg.networks;
}
// lib.optionalAttrs (svcCfg.command != [ ]) {
command = svcCfg.command;
}
// lib.optionalAttrs ((svcCfg.ports) != [ ]) {
ports = svcCfg.ports;
}
// lib.optionalAttrs ((svcCfg.volumes ++ fileVolumes) != [ ]) {
volumes = svcCfg.volumes ++ fileVolumes;
}
// lib.optionalAttrs (svcCfg.environment != { }) {
environment = svcCfg.environment;
}
// lib.optionalAttrs (svcCfg.environmentFiles != [ ]) {
env_file = map builtins.toString svcCfg.environmentFiles;
}
// lib.optionalAttrs (svcCfg.dependsOn != [ ]) {
depends_on = svcCfg.dependsOn;
}
// svcCfg.extraConfig;
# Build the full compose document attrset for a group.
mkComposeAttrs = groupName: grpCfg: fileVolumesByService:
let
networks =
if grpCfg.networks == { }
then { "${groupName}" = { driver = "bridge"; }; }
else grpCfg.networks;
in
{
services = lib.mapAttrs
(svcName: svcCfg:
mkComposeService groupName svcName svcCfg (fileVolumesByService."${svcName}" or [ ])
)
grpCfg.services;
networks = networks;
}
// lib.optionalAttrs (grpCfg.volumes != [ ]) {
volumes = lib.genAttrs grpCfg.volumes (_: { });
}
// grpCfg.extraConfig;
# Render compose.yml to the Nix store.
mkComposeFile = pkgs: groupName: grpCfg: fileVolumesByService:
(pkgs.formats.yaml { }).generate "compose.yml"
(mkComposeAttrs groupName grpCfg fileVolumesByService);
}
@@ -0,0 +1,86 @@
{ config, pkgs, lib, ... }:
let
containersCfg = config.skyg.nixos.common.containers;
cfg = config.skyg.nixos.common.container-services;
containerLib = import ./lib.nix { inherit lib pkgs; };
composeLib = import ./compose.nix { inherit lib; };
filesLib = import ./files.nix { inherit lib pkgs containerLib; };
systemdLib = import ./systemd.nix { inherit lib pkgs; };
isDocker = containerLib.isDocker containersCfg.runtime;
composeBin = containerLib.composeBin containersCfg.runtime;
runtimeService = containerLib.runtimeService isDocker;
enabledGroups = lib.filterAttrs (_: g: g.enable) cfg;
in
{
imports = [ ./options.nix ];
config = {
assertions = lib.optionals (enabledGroups != { }) [
{
assertion = config.virtualisation.docker.enable or false
|| config.virtualisation.podman.enable or false;
message = ''
skyg.nixos.common.container-services: at least one container runtime
must be enabled. Set skyg.nixos.common.containers.runtime (or enable
virtualisation.docker / virtualisation.podman directly).
'';
}
];
# Create tmpfiles rules for state dirs and file dirs
systemd.tmpfiles.rules =
(lib.mapAttrsToList
(_: grpCfg: "d ${grpCfg.stateDir} 0750 root root -")
enabledGroups)
++ (lib.mapAttrsToList
(groupName: grpCfg:
"d ${grpCfg.stateDir}/files 0755 root root -"
)
(lib.filterAttrs (_: grpCfg: filesLib.getAllFiles grpCfg != { }) enabledGroups)
);
# Systemd services: one compose unit + one env-reload unit per group with env files + one files unit per group with files
systemd.services =
lib.mapAttrs'
(groupName: grpCfg:
let
fileVolumes = filesLib.mkFileVolumesForGroup groupName grpCfg;
composeFile = composeLib.mkComposeFile pkgs groupName grpCfg fileVolumes;
hasFiles = filesLib.getAllFiles grpCfg != { };
in
lib.nameValuePair
"container-services-${groupName}"
(systemdLib.mkSystemdService groupName grpCfg composeFile composeBin runtimeService hasFiles))
enabledGroups
// lib.foldAttrs lib.recursiveUpdate { } (
lib.mapAttrsToList
(groupName: grpCfg:
systemdLib.mkEnvReloadService groupName)
(lib.filterAttrs
(_: grpCfg: containerLib.getAllEnvFiles grpCfg != [ ])
enabledGroups)
)
// lib.foldAttrs lib.recursiveUpdate { } (
lib.mapAttrsToList
(groupName: grpCfg:
filesLib.mkFilesService groupName grpCfg pkgs)
(lib.filterAttrs
(_: grpCfg: filesLib.getAllFiles grpCfg != { })
enabledGroups)
);
# Path units: one per group with env files
systemd.paths =
lib.foldAttrs lib.recursiveUpdate { } (
lib.mapAttrsToList
(groupName: grpCfg:
systemdLib.mkPathUnit groupName (containerLib.getAllEnvFiles grpCfg))
enabledGroups
);
};
}
@@ -0,0 +1,81 @@
{ lib, pkgs, containerLib }:
rec {
# Collect all files from all services in a group.
# Returns: { "<svcName>.<filename>" = { target = "..."; content = "..."; }; }
getAllFiles = grpCfg:
lib.foldAttrs lib.recursiveUpdate { }
(lib.mapAttrsToList
(svcName: svcCfg:
lib.mapAttrs'
(target: content:
let
filename = containerLib.pathToFilename target;
in
lib.nameValuePair
"${svcName}/${filename}"
{ inherit target content; }
)
svcCfg.files
)
grpCfg.services
);
# Build file volume mounts for a specific service.
# Returns: [ "/var/lib/container-services/<group>/files/<filename>:<target>:ro" ]
mkFileVolumesForService = groupName: svcCfg:
lib.mapAttrsToList
(target: _:
let
filename = containerLib.pathToFilename target;
hostPath = "/var/lib/container-services/${groupName}/files/${filename}";
in
"${hostPath}:${target}:ro"
)
svcCfg.files;
# Build file volume mounts for all services in a group.
# Returns: { "svcName" = [ "...mount..." ]; }
mkFileVolumesForGroup = groupName: grpCfg:
lib.mapAttrs
(svcName: svcCfg: mkFileVolumesForService groupName svcCfg)
grpCfg.services;
# Generate a shell script that writes all files for a group.
mkFilesScript = groupName: grpCfg:
let
filesMap = getAllFiles grpCfg;
writeCommands = lib.mapAttrsToList
(path: fileData:
let
filename = containerLib.pathToFilename fileData.target;
hostPath = "/var/lib/container-services/${groupName}/files/${filename}";
in
''
mkdir -p "$(dirname "${hostPath}")"
cat > "${hostPath}" <<'CONTENT'
${fileData.content}
CONTENT
chmod 0644 "${hostPath}"
''
)
filesMap;
in
lib.concatStringsSep "\n" writeCommands;
# Create a systemd service that writes files for a group.
# Only created if the group has files.
mkFilesService = groupName: grpCfg: pkgs:
let
filesMap = getAllFiles grpCfg;
in
lib.optionalAttrs (filesMap != { }) {
"container-services-${groupName}-files" = {
description = "Write custom files for container service group '${groupName}'";
serviceConfig = {
Type = "oneshot";
ExecStart = "${pkgs.bash}/bin/bash -c ${lib.escapeShellArg (mkFilesScript groupName grpCfg)}";
};
};
};
}
@@ -0,0 +1,33 @@
{ lib, pkgs }:
{
# Runtime dispatch
isDocker = runtime: runtime == "docker";
composeBin = runtime:
if lib.hasAttrByPath [ "docker" ] pkgs
then
(if runtime == "docker"
then "${pkgs.docker-compose}/bin/docker-compose"
else "${pkgs.podman-compose}/bin/podman-compose")
else
(if runtime == "docker"
then "docker-compose"
else "podman-compose");
runtimeService = isDocker:
if isDocker then "docker.service" else "podman.service";
# Collect all env files from all services in a group
getAllEnvFiles = grpCfg:
lib.concatLists
(lib.attrValues
(lib.mapAttrs (_: svcCfg: svcCfg.environmentFiles) grpCfg.services));
# Sanitize a path into a valid filename
pathToFilename = target:
lib.strings.sanitizeDerivationName (
lib.strings.removePrefix "/" target
| > builtins.replaceStrings [ "/" ] [ "-" ]
);
}
@@ -0,0 +1,152 @@
{ lib }:
{
options.skyg.nixos.common.container-services = lib.mkOption {
description = ''
Compose-style container service groups.
Each group is rendered to a compose.yml in the Nix store, staged into
its stateDir on activation, and managed by a single systemd oneshot unit:
container-services-<group>.service
See modules/nixos/common/containers/user-guide.md for full documentation.
'';
default = { };
type = lib.types.attrsOf (lib.types.submodule ({ name, ... }: {
options = {
enable = lib.mkEnableOption "this container service group" // { default = true; };
stateDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/container-services/${name}";
description = "Directory where the staged compose.yml lives at runtime.";
};
timeoutStopSec = lib.mkOption {
type = lib.types.int;
default = 120;
description = "Seconds to wait for 'compose down' before forcibly killing containers.";
};
services = lib.mkOption {
description = "Container services in this group (maps to compose services: block).";
default = { };
type = lib.types.attrsOf (lib.types.submodule {
options = {
image = lib.mkOption {
type = lib.types.str;
description = "Container image (registry/name:tag).";
};
command = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Entrypoint command override (compose command:).";
};
ports = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [ "8642:8642" ];
description = "Port mappings in HOST:CONTAINER format.";
};
volumes = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [ "/var/lib/hermes:/opt/data" ];
description = "Volume mounts in src:dst[:opts] format.";
};
environment = lib.mkOption {
type = lib.types.attrsOf lib.types.str;
default = { };
description = "Environment variables as key/value pairs.";
};
environmentFiles = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = ''
Paths to env files loaded by compose at runtime.
Accepts runtime paths such as agenix secret paths
(e.g. config.age.secrets.my-secret.path).
Changes to these files will trigger an automatic restart.
'';
};
dependsOn = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Sibling service names that must start first (compose depends_on:).";
};
restart = lib.mkOption {
type = lib.types.str;
default = "unless-stopped";
description = "Compose restart policy.";
};
networks = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = ''
Networks to join. Empty list = attach to the group's
auto-created bridge network (named after the group).
'';
};
files = lib.mkOption {
type = lib.types.attrsOf lib.types.str;
default = { };
description = ''
Custom files to mount into the container.
Key = target path inside container (e.g. "/opt/data/config.yaml")
Value = file content as a string.
Files are written to /var/lib/container-services/<group>/files/ on the host
and bind-mounted read-only into the container at the specified paths.
'';
};
extraConfig = lib.mkOption {
type = lib.types.attrsOf lib.types.anything;
default = { };
description = ''
Free-form attrset merged directly into the compose service
block. Use this for keys not modelled above:
shm_size, cap_add, devices, healthcheck, etc.
'';
};
};
});
};
volumes = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Named volumes declared at the top level of the compose document.";
};
networks = lib.mkOption {
type = lib.types.attrsOf lib.types.anything;
default = { };
description = ''
Network definitions for the top-level compose networks: block.
Empty = auto-create a bridge network named after the group.
'';
};
extraConfig = lib.mkOption {
type = lib.types.attrsOf lib.types.anything;
default = { };
description = "Free-form attrset merged into the top-level compose document.";
};
};
}));
};
}
@@ -0,0 +1,51 @@
{ lib, pkgs }:
{
# Create a systemd oneshot service that manages the compose stack.
mkSystemdService = groupName: grpCfg: composeFile: composeBin: runtimeService: hasFiles:
let
stateDir = grpCfg.stateDir;
fileServiceDep = if hasFiles then "container-services-${groupName}-files.service" else null;
in
{
description = "Container service group '${groupName}'";
wantedBy = [ "multi-user.target" ];
after = [ runtimeService "network-online.target" "agenix.service" ]
++ lib.optional hasFiles fileServiceDep;
requires = [ runtimeService ]
++ lib.optional hasFiles fileServiceDep;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
TimeoutStopSec = grpCfg.timeoutStopSec;
ExecStartPre = "${pkgs.coreutils}/bin/cp ${composeFile} ${stateDir}/compose.yml";
ExecStart = "${composeBin} -p ${groupName} -f ${stateDir}/compose.yml up -d --remove-orphans";
ExecStop = "${composeBin} -p ${groupName} -f ${stateDir}/compose.yml down";
};
};
# Create a path unit that watches env files for changes.
mkPathUnit = groupName: envFiles:
lib.optionalAttrs (envFiles != [ ]) {
"container-services-${groupName}-env-reload" = {
description = "Watch env files for container service group '${groupName}'";
pathConfig = {
PathChanged = map toString envFiles;
Unit = "container-services-${groupName}-env-reload.service";
};
wantedBy = [ "multi-user.target" ];
};
};
# Create a service that restarts the compose stack when env files change.
mkEnvReloadService = groupName:
{
"container-services-${groupName}-env-reload" = {
description = "Restart container service group '${groupName}' on env file changes";
serviceConfig = {
Type = "oneshot";
ExecStart = "${pkgs.systemd}/bin/systemctl restart container-services-${groupName}.service";
};
};
};
}
+1 -1
View File
@@ -4,7 +4,7 @@
imports = [
./docker.nix
./podman.nix
./container-services.nix
./container-services
];
options = {
skyg.nixos.common.containers = {
@@ -101,6 +101,34 @@ cat /nix/store/…-compose.yml
If the store file is wrong, the bug is in your Nix options — rebuild with
`nixos-rebuild build` and inspect the new store path before switching.
## Custom Files
Mount custom files into containers via the `files` option:
```nix
services.app = {
image = "my/app";
files = {
"/etc/app/config.yaml" = ''
server:
port: 8080
'';
"/usr/local/bin/startup.sh" = ''
#!/bin/bash
echo "Starting..."
'';
};
};
```
Files are:
- Written to `/var/lib/container-services/<group>/files/` on the host
- Mounted read-only into the container at the specified paths
- Updated automatically when you rebuild
- Changes trigger an automatic restart (via the `container-services-<group>-files` unit)
---
## Limitations
- **One unit per group.** No per-container systemd units. Use `docker compose logs` for
Binary file not shown.