Nix.nix 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. {
  2. # Name of our deployment
  3. network.description = "HelloWorld";
  4. # Enable rolling back to previous versions of our infrastructure
  5. network.enableRollback = true;
  6. # It consists of a single server named 'helloserver'
  7. helloserver =
  8. # Every server gets passed a few arguments, including a reference
  9. # to nixpkgs (pkgs)
  10. { config, pkgs, ... }:
  11. let
  12. # We import our custom packages from ./default passing pkgs as argument
  13. packages = import ./default.nix { pkgs = pkgs; };
  14. # This is the nodejs version specified in default.nix
  15. nodejs = packages.nodejs;
  16. # And this is the application we'd like to deploy
  17. app = packages.app;
  18. in
  19. {
  20. # We'll be running our application on port 8080, because a regular
  21. # user cannot bind to port 80
  22. # Then, using some iptables magic we'll forward traffic designated to port 80 to 8080
  23. networking.firewall.enable = true;
  24. # We will open up port 22 (SSH) as well otherwise we're locking ourselves out
  25. networking.firewall.allowedTCPPorts = [ 80 8080 22 ];
  26. networking.firewall.allowPing = true;
  27. # Port forwarding using iptables
  28. networking.firewall.extraCommands = ''
  29. iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
  30. '';
  31. # To run our node.js program we're going to use a systemd service
  32. # We can configure the service to automatically start on boot and to restart
  33. # the process in case it crashes
  34. systemd.services.helloserver = {
  35. description = "Hello world application";
  36. # Start the service after the network is available
  37. after = [ "network.target" ];
  38. # We're going to run it on port 8080 in production
  39. environment = { PORT = "8080"; };
  40. serviceConfig = {
  41. # The actual command to run
  42. ExecStart = "${nodejs}/bin/node ${app}/server.js";
  43. # For security reasons we'll run this process as a special 'nodejs' user
  44. User = "nodejs";
  45. Restart = "always";
  46. };
  47. };
  48. # And lastly we ensure the user we run our application as is created
  49. users.extraUsers = {
  50. nodejs = { };
  51. };
  52. };
  53. }