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