chore: add docker stack integration with improved service management

This commit is contained in:
2026-01-01 02:25:05 -05:00
parent 46ac5a72d0
commit 0b4e9e092d

View File

@@ -1,36 +1,50 @@
{ config, lib, pkgs, ... }: { config, pkgs, lib, ... }:
with lib; with lib;
{ {
options.services.myDockerStacks = mkOption { options.services.dockerStacks = mkOption {
type = types.attrsOf (types.submodule { type = types.attrsOf (types.submodule {
options = { options = {
path = mkOption { type = types.path; }; path = mkOption { type = types.str; };
envFile = mkOption { type = types.nullOr types.path; default = null; };
ports = mkOption { type = types.listOf types.int; default = [ ]; }; ports = mkOption { type = types.listOf types.int; default = [ ]; };
}; };
}); });
default = {}; default = {};
description = "Attribute set of docker-compose stacks to run.";
}; };
config = { config = {
# Generate the systemd services based on the options provided above virtualisation.docker.enable = true;
virtualisation.docker.daemon.settings.dns = [ "1.1.1.1" "8.8.8.8" ];
networking.firewall.allowedTCPPorts = flatten (mapAttrsToList (name: value: value.ports) config.services.dockerStacks);
systemd.services = mapAttrs' (name: value: nameValuePair "${name}_stack" { systemd.services = mapAttrs' (name: value: nameValuePair "${name}_stack" {
description = "${name} via Docker Compose"; description = "Docker Compose stack: ${name}";
after = [ "network-online.target" "docker.service" ];
wants = [ "network-online.target" "docker.service" ]; # Added 'docker.socket' to both after and wants to ensure the API is reachable
after = [ "network.target" "docker.service" "docker.socket" "agenix.service" ];
wants = [ "docker.socket" "agenix.service" ];
requires = [ "docker.service" ];
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
serviceConfig = { serviceConfig = {
Type = "oneshot";
WorkingDirectory = value.path; WorkingDirectory = value.path;
ExecStartPre = "${pkgs.docker-compose}/bin/docker-compose down"; User = "root";
ExecStart = "${pkgs.docker-compose}/bin/docker-compose up -d";
# This line forces the service to wait until the docker socket is actually responsive
ExecStartPre = "${pkgs.bash}/bin/bash -c 'while [ ! -S /var/run/docker.sock ]; do sleep 1; done'";
ExecStart = "${pkgs.docker-compose}/bin/docker-compose up -d --remove-orphans";
ExecStop = "${pkgs.docker-compose}/bin/docker-compose down"; ExecStop = "${pkgs.docker-compose}/bin/docker-compose down";
RemainAfterExit = true; RemainAfterExit = true;
};
}) config.services.myDockerStacks;
# Automatically open firewall ports # Ensure the environment file is passed correctly
networking.firewall.allowedTCPPorts = flatten (mapAttrsToList (n: v: v.ports) config.services.myDockerStacks); EnvironmentFile = mkIf (value.envFile != null) [ value.envFile ];
};
}) config.services.dockerStacks;
}; };
} }