Traefik

From NixOS Wiki
Revision as of 23:21, 22 October 2024 by Dander (talk | contribs) (first draft, will revisit tomorrow)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Traefik is a reverse proxy and load balancer.

Installation

To install Traefik, add the following to your NixOS configuration:

services.traefik.enable = true;

More options are available.

Configuration

Using Nixlang (Nix the language)

  services.traefik = {
    enable = true;

    staticConfigOptions = {
      entryPoints = {
        web = {
          address = ":80";
          asDefault = true;
          http.redirections.entrypoint = {
            to = "websecure";
            scheme = "https";
          };
        };

        websecure = {
          address = ":443";
          asDefault = true;
          http.tls.certResolver = "letsencrypt";
        };

        log = {
          level = "INFO";
          filePath = "${config.services.traefik.dataDir}/traefik.log";
          format = "json";
        };

        certificatesResolvers.letsencrypt.acme = {
          email = "postmaster@YOUR.DOMAIN";
          storage = "${config.services.traefik.dataDir}/acme.json";
          httpChallenge.entryPoint = "web";
        };
      };

      api.dashboard = true;
      # Access the Traefik dashboard on <Traefik IP>:8080 of your server
      # api.insecure = true;
    };

    dynamicConfigOptions = {
      http.routers = {};
      http.services = {};
    };
  };

Using files

If you are migrating from a Non-NixOS system, you might be interested in the staticConfigFile and dynamicConfigFile options.

You can set staticConfigFile like this:

services.traefik.staticConfigFile = ./static_config.toml;

But you need to be careful about how you set the dynamicConfigFile, if you pass a path, your "dynamic" config file will point to a path in the Nix store, which would change on every update to the file, so you would need to reload Traefik for the changes to take effect, which defeats the point of using the dynamic config file. A way to avoid this is to use etc.environment:

# Note the quotes around the path!
services.traefik.dynamicConfigFile = "/etc/traefik/dynamic_config.toml";
# If you use staticConfigFile instead, update your file provider accordingly.
services.traefik.staticConfigOptions.providers.file.watch = true;

environment.etc."traefik/dynamic_config.toml" = {
    user = config.systemd.services.traefik.serviceConfig.User;
    group = config.systemd.services.traefik.serviceConfig.Group;
    mode = "400";
    text = ''
        # ...
    '';
    # Or,
    # source = ./dynamic_config.toml     
};

Additionally, you can not use a ...ConfigFile option and a ...ConfigOptions for either static or dynamic configuration. The file options always take precedence over the options options, which are ignored.