How to Configure a Custom NixOS Service with Environment Variables

Hello NixOS Community,

I’m currently working on setting up a custom service in NixOS and would like some guidance on configuring it with environment variables.

Here’s what I’m trying to achieve:

  • Service Definition: How do I define a custom service in my configuration.nix with specific environment variables?
  • Environment Variables: What is the best way to pass environment variables to the service? Should they be included directly in the service definition or managed separately?
  • Testing and Debugging: Are there any recommended practices for testing and debugging custom services to ensure they are picking up the environment variables correctly?

I also check this: https://discourse.nixos.org/t/home-manager-flake-and-configuration-how-to-rebuild-the-whole-environment-with-just-nixos-rebuild-switcsnowflake But I have not found any solution. Any tips, examples, or resources would be greatly appreciated. Thank you in advance for your assistance!

Best regards

Roughly like this:

systemd.services.<name> = {
  path = [ some-package ];
  script = "some-binary";
  environment = {
    FOO = "BAR";
  };
};

For more options, check the systemd service options, and make sure to read the systemd docs.

Depends on the variable and the application. Above is usually what you want, but don’t put secrets in there - they will be stored world-readable.

That’s testing that NixOS works, which upstream is already doing for you, so probably superfluous.

Testing that your application behaves correctly when given environment variables should be done at the application project level.

You can write an integration test that asserts your service works as you expect it to, and give it specific environment variables as part of that, though: NixOS Manual

1 Like