docs(chapters): import chapters 02 through 05 with assets and navigation
- Import Motivation, The Big Picture, Setup, and Web Server from upstream manuscript - Add CC BY-NC-SA 4.0 attribution banners and Leanpub support links - Convert Leanpub blurb syntax to GitHub callout alerts (> [!NOTE], > [!WARNING]) - Bundle and link screenshot assets for Web Server chapter - Add chapter-to-chapter sequential navigation footers
This commit is contained in:
1 parent
9086cfcc03
commit
5e88b06fdd
6 files changed
+1127
No files matched your search
@@ -0,0 +1,214 @@
|
||||
# 02. Motivation
|
||||
|
||||
> [!NOTE]
|
||||
> **Attribution:** Adapted from [*NixOS in Production*](https://github.com/Gabriella439/nixos-in-production) by Gabriella Gonzalez ([CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/)).
|
||||
> Support the author by purchasing the official edition on [Leanpub](https://leanpub.com/nixos-in-production).
|
||||
|
||||
---
|
||||
|
||||
Some NixOS users might try to "convert" others to NixOS using a pitch that goes something like this:
|
||||
|
||||
> NixOS is a Linux distribution built on top of the Nix package manager. It uses declarative configuration and allows reliable system upgrades.
|
||||
>
|
||||
> Source: [Wikipedia - NixOS](https://en.wikipedia.org/wiki/NixOS)
|
||||
|
||||
This sort of feature-oriented description explains what NixOS *does*, but does not quite explain what NixOS *is for*. What sort of useful things can you do with NixOS? When is NixOS the best solution? What types of projects, teams, or organizations should prefer using NixOS over other the alternatives?
|
||||
|
||||
Come to think of it, what *are* the alternatives? Is NixOS supposed to replace Debian? Or Docker? Or Ansible? Or Vagrant? Where does NixOS fit in within the modern software landscape?
|
||||
|
||||
In this chapter I'll help you better understand when you should recommend NixOS to others and (just as important!) when you should gently nudge people away from NixOS. Hopefully this chapter will improve your overall understanding of NixOS's "niche".
|
||||
|
||||
## Desktop vs. Server
|
||||
|
||||
The title of this book might have tipped you off that I will endorse NixOS for use as a server operating system rather than a desktop operating system.
|
||||
|
||||
I would not confidently recommend NixOS as a desktop operating system because:
|
||||
|
||||
- *NixOS expects users to be developers who are more hands-on with their system*
|
||||
|
||||
NixOS does not come preinstalled on most computers and the installation guide assumes quite a bit of technical proficiency. For example, NixOS is typically configured via text files and upgrades are issued from the command line.
|
||||
|
||||
|
||||
- *Nixpkgs doesn't enjoy mainstream support for desktop-oriented applications*
|
||||
|
||||
… especially games and productivity tools. Nixpkgs is a fairly large software distribution, especially compared to other Linux software distributions, but most desktop applications will not support the Nix ecosystem out-of-the-box.
|
||||
|
||||
|
||||
- *The NixOS user experience differs from what most desktop users expect*
|
||||
|
||||
Most desktop users (especially non-technical users) expect to install packages by either downloading the package from the publisher's web page or by visiting an "app store" of some sort. They don't expect to modify a text configuration file in order to install package.
|
||||
|
||||
|
||||
However, the above limitations don't apply when using NixOS as a server
|
||||
operating system:
|
||||
|
||||
- *Servers are managed by technical users comfortable with the command-line*
|
||||
|
||||
Server operating systems are often [headless](https://en.wikipedia.org/wiki/Headless_computer) machines that only support a command-line interface. In fact, a typical Ops team would likely frown upon managing a server in any other way.
|
||||
|
||||
|
||||
- *Nixpkgs provides amazing support for server-oriented software and services*
|
||||
|
||||
`nginx`, `postgres`, `redis`, … you name it, Nixpkgs most likely has the service you need and it's a dream to set up.
|
||||
|
||||
|
||||
- *End users can more easily self-serve if they stray from the beaten path*
|
||||
|
||||
Server-oriented software is more likely to be open source than desktop-oriented software and therefore easier to package.
|
||||
|
||||
|
||||
Furthermore, NixOS possesses several unique advantages compared to other server-oriented operating systems:
|
||||
|
||||
- *NixOS can be managed entirely declaratively*
|
||||
|
||||
You can manage every single aspect of a NixOS server using a single, uniform, declarative option system. This goes hand-in-hand with [GitOps](https://www.redhat.com/en/topics/devops/what-is-gitops) for managing a fleet of machines (which I'll cover in a future chapter).
|
||||
|
||||
|
||||
- *NixOS upgrades are fast, safe and reliable*
|
||||
|
||||
Upgrades are atomic, meaning that you can't leave a system in an unrecoverable state by canceling the upgrade midway (e.g. `Ctrl-C` or loss of power). You can also build the desired system ahead of time if you want to ensure that the upgrade is quick and smooth.
|
||||
|
||||
|
||||
- *NixOS systems are lean, lean, lean*
|
||||
|
||||
If you like Alpine Linux then you'll *love* NixOS. NixOS systems tend to be very light on disk, memory, and CPU resources because you only pay for what you use. You can achieve astonishingly small system footprints whether you run services natively on the host or inside of containers.
|
||||
|
||||
|
||||
- *NixOS systems have better security-related defaults*
|
||||
|
||||
You get several security improvements for free or almost free by virtue of using NixOS. For example, your system's footprint is immutable and internal references to filepaths or executables are almost always fully qualified.
|
||||
|
||||
|
||||
## On-premises vs. Software as a service
|
||||
|
||||
"Server operating systems" is still a fairly broad category and we can narrow things down further depending on where we deploy the server:
|
||||
|
||||
- *On-premises ("on-prem" for short)*
|
||||
|
||||
"On-premises" software runs within the end user's environment. For example, if the software product is a server then an on-premises deployment runs within the customer's data center, either as a virtual machine or a physical rack server.
|
||||
|
||||
|
||||
- *Software as a service ("SaaS" for short)*
|
||||
|
||||
The opposite of on-premises is "off-premises" (more commonly known as "software as a service"). This means that you centrally host your software, either in your data center or in the cloud, and customers interact with the software via a web interface or API.
|
||||
|
||||
|
||||
NixOS is better suited for SaaS than on-prem deployments, because NixOS fares worse in restricted network environments where network access is limited or unavailable.
|
||||
|
||||
You can still deploy NixOS for on-prem deployments and I will cover that in a later chapter, but you will have a much better time using NixOS for SaaS deployments.
|
||||
|
||||
## Virtualization
|
||||
|
||||
You might be interested in how NixOS fares with respect to virtualization or containers, so I'll break things down into these four potential use cases:
|
||||
|
||||
- *NixOS without virtualization*
|
||||
|
||||
You can run NixOS on a bare metal machine (e.g. a desktop computer or physical rack server) without any virtual machines or containers. This implies that services run directly on the bare metal machine.
|
||||
|
||||
|
||||
- *NixOS as a host operating system*
|
||||
|
||||
You can also run NixOS on a bare metal machine (i.e the "host") but then on that machine you run containers or virtual machines (i.e. the "guests"). Typically, you do this if you want services to run inside the guest machines.
|
||||
|
||||
|
||||
- *NixOS as a guest operating system*
|
||||
|
||||
Virtual machines or [OS containers](https://blog.risingstack.com/operating-system-containers-vs-application-containers/) can run a fully-fledged operating system inside of them, which can itself be a NixOS operating system. I consider this similar in spirit to the "NixOS without virtualization" case above because in both cases the services are managed by NixOS.
|
||||
|
||||
|
||||
- *Application containers*
|
||||
|
||||
Containers technically do not need to run an entire operating system and can instead run a single process (e.g. one service). You can do this using Nixpkgs, which provides support for building application containers.
|
||||
|
||||
|
||||
So which use cases are NixOS/Nixpkgs well-suited for? If I had to rank these deployment models then my preference (in descending order) would be:
|
||||
|
||||
- *NixOS as a guest operating system*
|
||||
|
||||
Specifically, this means that you would run NixOS as a virtual machine on a cloud provider (e.g. AWS) and all of your services run within that NixOS guest machine with no intervening containers.
|
||||
|
||||
I prefer this because this is the leanest deployment model and the lowest maintenance to administer.
|
||||
|
||||
|
||||
- *NixOS without virtualization*
|
||||
|
||||
This typically entails running NixOS on a physical rack server and you still use NixOS to manage all of your services without containers.
|
||||
|
||||
This can potentially be the most cost-effective deployment model if you're willing to manage your own hardware (including RAID and backup/restore) or you operate your own data center.
|
||||
|
||||
|
||||
- *NixOS as a host operating system - Static containers*
|
||||
|
||||
NixOS also works well when you want to statically specify a set of containers to run. Not only can NixOS run Docker containers or OCI containers, but NixOS also provides special support for "NixOS containers" (which are `systemd-nspawn` containers under the hood) or application containers built by Nixpkgs.
|
||||
|
||||
I rank this lower than "NixOS without virtualization" because NixOS obviates some (but not all) of the reasons for using containers. In other words, once you switch to using NixOS you might find that you can do just fine without containers or at least use them much more sparingly.
|
||||
|
||||
|
||||
- *NixOS as a host operating system - Dynamic containers*
|
||||
|
||||
You can also use NixOS to run containers dynamically, but NixOS is not special in this regard. At best, NixOS might simplify administering a container orchestration service (e.g. `kubernetes`).
|
||||
|
||||
|
||||
- *Application containers sans NixOS*
|
||||
|
||||
This is technically a use case for Nixpkgs and not NixOS, but I mention it for completeness. Application containers built by Nixpkgs work best if you are trying to introduce the Nix ecosystem (but not NixOS) within a legacy environment.
|
||||
|
||||
However, you lose out on the benefits of using NixOS because, well, you're no longer using NixOS.
|
||||
|
||||
|
||||
## The killer app for NixOS
|
||||
|
||||
Based on the above guidelines, we can outline the ideal use case for NixOS:
|
||||
|
||||
- NixOS shines as a server operating system for SaaS deployments
|
||||
|
||||
- Services should preferably be statically defined via the NixOS configuration
|
||||
|
||||
- NixOS can containerize these services, but it's simpler to skip the containers
|
||||
|
||||
If your deployment model matches that outline then NixOS is not only a safe choice, but likely the best choice! You will be in great company if you use NixOS in this way.
|
||||
|
||||
You can still use NixOS in other capacities, but the further you depart from the above "killer app" the more you will need to roll up your sleeves.
|
||||
|
||||
## Profile of a NixOS adopter
|
||||
|
||||
NixOS is a [DevOps](https://www.atlassian.com/devops) tool, meaning that NixOS blurs the boundary between software development and operations.
|
||||
|
||||
The reason why NixOS fits the DevOps space so well is because NixOS unifies all aspects of managing a system through the uniform NixOS options interface. In other words, you can use NixOS options to configure operational details (e.g. RAID, encryption, boot loaders) and also software development details (e.g. dependency versions, patches, and even small amounts of inline code).
|
||||
|
||||
This means that a DevOps engineer or DevOps team is best situated to introduce NixOS within an engineering organization.
|
||||
|
||||
> [!NOTE]
|
||||
> DevOps is more of a set of cultural practices than a team, but some organizations explicitly create a DevOps team or hire engineers for their DevOps expertise in order to support tools (like NixOS) that enable those cultural practices.
|
||||
|
||||
## What does NixOS replace?
|
||||
|
||||
If NixOS is a server operating system, does that mean that NixOS competes with other server operating systems like Ubuntu Server, Debian or Fedora? Not exactly.
|
||||
|
||||
NixOS competes more with the Docker ecosystem, meaning that a lot of the value that NixOS adds overlaps with Docker:
|
||||
|
||||
- *NixOS supports declarative system specification*
|
||||
|
||||
… analogous to `docker compose`.
|
||||
|
||||
|
||||
- *NixOS provides better isolation*
|
||||
|
||||
… analogous to containers.
|
||||
|
||||
|
||||
- *NixOS uses the Nix package manager to declaratively assemble software*
|
||||
|
||||
… analogous to `Dockerfile`s.
|
||||
|
||||
|
||||
You *can* use NixOS in conjunction with Docker containers since NixOS supports declaratively launching containers, but you probably want to avoid buying further into the broader Docker ecosystem if you use NixOS. You don't want to be in a situation where your engineering organization fragments and does everything in two different ways: the NixOS way and the Docker way.
|
||||
|
||||
> [!NOTE]
|
||||
> For those familiar with the Gentoo Linux distribution, **NixOS is like Gentoo, but for Docker**[^1]. Similar to Gentoo, NixOS is an operating system that provides unparalleled control over the machine while targeting use cases and workflows similar to the Docker ecosystem.
|
||||
|
||||
[^1]: Thank you to [Adam Gordon Bell](https://adamgordonbell.com/) for this analogy
|
||||
|
||||
---
|
||||
|
||||
**Previous:** [01. Introduction](01-introduction.md) · **Index:** [Table of Contents](../README.md) · **Next:** [03. The Big Picture](03-big-picture.md)
|
||||
@@ -0,0 +1,266 @@
|
||||
# 03. The Big Picture
|
||||
|
||||
> [!NOTE]
|
||||
> **Attribution:** Adapted from [*NixOS in Production*](https://github.com/Gabriella439/nixos-in-production) by Gabriella Gonzalez ([CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/)).
|
||||
> Support the author by purchasing the official edition on [Leanpub](https://leanpub.com/nixos-in-production).
|
||||
|
||||
---
|
||||
|
||||
Before diving in further you might want to get some idea of what a "real" NixOS software enterprise looks like. Specifically:
|
||||
|
||||
- What are the guiding principles for a NixOS-centric software architecture?
|
||||
|
||||
- How does a NixOS-centric architecture differ from other architectures?
|
||||
|
||||
- What would a "NixOS team" need to be prepared to support and maintain?
|
||||
|
||||
Here I'll do my best to answer those questions so that you can get a better idea of what you would be signing up for.
|
||||
|
||||
## The Zen of NixOS
|
||||
|
||||
I like to use the term "master cue" to denote an overarching sign that indicates that you're doing things right. This master cue might not tell you *how* to do things right, but it can still provide a high-level indicator of whether you are on the right track.
|
||||
|
||||
The master cue for NixOS is very similar to the master cue for the Nix ecosystem, which is this:
|
||||
|
||||
> Every common build/test/deploy-related activity should be possible with at most one command using Nix's command line interface.
|
||||
|
||||
I say "*at most* one command" because some activities (like continuous deployment) should ideally require no human intervention at all. However, activities that do require human intervention should in principle be compressible into a single Nix command.
|
||||
|
||||
I can explain this by providing an example of a development workflow that *disregards* this master cue:
|
||||
|
||||
Suppose that you want to test your local project's changes within the context of some larger system at work (i.e. an [integration test](https://en.wikipedia.org/wiki/Integration_testing)). Your organization's process for testing your code might hypothetically look like this:
|
||||
|
||||
- Create and publish a branch in version control recording your changes
|
||||
|
||||
- Manually trigger some workflow to build a software artifact containing your changes
|
||||
|
||||
- Update some configuration file to reference the newly-built software artifact
|
||||
|
||||
- Run the appropriate integration test
|
||||
|
||||
Now what if I told you that the entire integration testing process from start to finish could be:
|
||||
|
||||
- Run `nix flake check`
|
||||
|
||||
In other words:
|
||||
|
||||
- *There would be no need to create or publish your branch*
|
||||
|
||||
You could test uncommitted changes straight from your local project checkout.
|
||||
|
||||
|
||||
- *There would be no multi-step publication process*
|
||||
|
||||
All of the intermediate build products and internal references would be handled transparently by the Nix build tool.
|
||||
|
||||
|
||||
- *The test itself would be managed by the Nix build tool*
|
||||
|
||||
In other words, Nix would treat your integration test no differently than any other build product. Tests and their outputs *are* build products.
|
||||
|
||||
|
||||
- *There would be no need to select the appropriate tests to rerun*
|
||||
|
||||
The Nix build tool would automatically infer which tests depended on your project and rerun those. Other test runs and their results would be cached if their dependency tree did not include your changes.
|
||||
|
||||
|
||||
Some of these potential improvements are not specific to the Nix ecosystem. After all, you could attempt to create a script that automates the more painstaking multi-step process. However, you would likely need to reinvent large portions of the Nix ecosystem for this automation to be sufficiently robust and efficient. For example:
|
||||
|
||||
- *Do you maintain a file server for storing intermediate build products?*
|
||||
|
||||
You're likely implementing your own version of the Nix store and caching system
|
||||
|
||||
|
||||
- *Do you generate unique labels for build products to isolate parallel workflows?*
|
||||
|
||||
In the best case scenario, you label build products by a hash of their dependencies and you've reinvented the Nix store's hashing scheme. In the worst case scenario you're doing something less accurate (e.g. using timestamps in the labels instead of hashes).
|
||||
|
||||
|
||||
- *Do you have a custom script that updates references to these build products?*
|
||||
|
||||
This would be reinventing Nix's language support for automatically updating dependency references.
|
||||
|
||||
|
||||
- *Do you need to isolate your integration tests or run them in parallel?*
|
||||
|
||||
You would likely reimplement the NixOS test framework.
|
||||
|
||||
|
||||
You can save yourself a lot of headaches by taking time to learn and use the Nix ecosystem as idiomatically as possible instead of learning these lessons the hard way.
|
||||
|
||||
<a id="gitops"></a>
|
||||
## GitOps
|
||||
|
||||
NixOS exemplifies the [Infrastructure as Code (IaC)](https://en.wikipedia.org/wiki/Infrastructure_as_code) paradigm, meaning that every aspect of your organization (including hardware/systems/software) is stored in code or configuration files that are the source of truth for how everything is built. In particular, you don't make undocumented changes to your infrastructure that cause it to diverge from what is recorded within those files.
|
||||
|
||||
This book will espouse a specific flavor of Infrastructure of Code known as [GitOps](https://about.gitlab.com/topics/gitops/) where:
|
||||
|
||||
- *The code and configuration files are (primarily) declarative*
|
||||
|
||||
In other words, they tend to specify the desired state of the system rather than a sequence of steps to get there.
|
||||
|
||||
|
||||
- *These files are stored in version control*
|
||||
|
||||
Proponents of this approach most commonly use `git` as their version control software, which is why it's called "GitOps".
|
||||
|
||||
|
||||
- *Pull requests are the change management system*
|
||||
|
||||
In other words, the pull request review process determines whether you have sufficient privileges, enough vetting, or the correct approvals from relevant maintainers.
|
||||
|
||||
|
||||
## DevOps
|
||||
|
||||
NixOS also exemplifies the [DevOps](https://en.wikipedia.org/wiki/DevOps) principle of breaking down boundaries between software developers ("Dev") and operations ("Ops"). Specifically, NixOS goes further in this regard than most other tools by unifying both software configuration and system configuration underneath the NixOS option system. These NixOS options fall into roughly three categories:
|
||||
|
||||
- *Systems configuration*
|
||||
|
||||
These are options that are mostly interesting to operations engineers, such as:
|
||||
|
||||
- log rotation policies
|
||||
- kernel boot parameters
|
||||
- disk encryption settings
|
||||
|
||||
|
||||
- *Hybrid systems/software options*
|
||||
|
||||
These are options that live in the grey area between Dev and Ops, such as:
|
||||
|
||||
- Service restart policies
|
||||
- Networking
|
||||
- Credentials/secrets management
|
||||
|
||||
|
||||
- *Software configuration*
|
||||
|
||||
These are options that are mostly interesting to software engineers, such as:
|
||||
|
||||
- Patches
|
||||
- Command-line arguments
|
||||
- Environment variables
|
||||
|
||||
|
||||
In extreme cases, you can even embed non-Nix code inside of Nix and do "pure software development". In other words, you can author inline code written within another language inside of a NixOS configuration file. I'll include one example of this later on in the "Our first web server" chapter.
|
||||
|
||||
## Architecture
|
||||
|
||||
A NixOS-centric architecture tends to have the following key pieces of infrastructure:
|
||||
|
||||
- *Version control*
|
||||
|
||||
If you're going to use GitOps then you had better use `git`! More specifically, you'll likely use a `git` hosting provider like [GitHub](https://github.com/) or [GitLab](https://about.gitlab.com/) which supports pull requests and continuous integration.
|
||||
|
||||
Most companies these days use version control, so this is not a surprising requirement.
|
||||
|
||||
|
||||
- *Product servers*
|
||||
|
||||
These are the NixOS servers that actually host your product-related services.
|
||||
|
||||
|
||||
- *A central build server (the "hub")*
|
||||
|
||||
This server initiates builds for continuous integration, which are delegated to builders.
|
||||
|
||||
|
||||
- *Builders for each platform*
|
||||
|
||||
These builders perform the actual Nix builds. However, remember that integration tests will be Nix builds, too, so these builders also run integration tests.
|
||||
|
||||
These builders will come in two flavors:
|
||||
|
||||
- Builders for the hub (the "spokes")
|
||||
- Builders for developers to use
|
||||
|
||||
|
||||
- *A cache*
|
||||
|
||||
In simpler setups the "hub" can double as a cache, but as you grow you will likely want to upload build products to a dedicated cache.
|
||||
|
||||
|
||||
- *One or more "utility" servers*
|
||||
|
||||
A "utility" server is a NixOS server that you can use to host IT infrastructure and miscellaneous utility services to support developers (e.g. web pages, chat bots).
|
||||
|
||||
This server will play a role analogous to a container engine or virtual machine hypervisor in other software architectures, except that we won't necessarily be using virtual machines or containers: many things will run natively on the host as NixOS services. Of course, you can also use this machine to run a container engine or hypervisor in addition to running things natively on the host.
|
||||
|
||||
> [!WARNING]
|
||||
> A "utility" server should **not** be part of your continuous integration or continuous deployment pipeline. You should think of such a server as a "junk drawer" for stuff that does not belong in CI/CD.
|
||||
|
||||
Moreover, you will either need a cloud platform (e.g. [AWS](https://aws.amazon.com/)) or data center for hosting these machines. In this book we'll primarily focus on hosting infrastructure on AWS.
|
||||
|
||||
These are not the only components you will need to build out your product, but these should be the only components necessary to support DevOps workflows, including continuous integration and continuous deployment.
|
||||
|
||||
Notably absent from the above list are:
|
||||
|
||||
- *Container-specific infrastructure*
|
||||
|
||||
A NixOS-centric architecture already mitigates some of the need for containerizing services, but the architecture doesn't change much even if you do use containers, because containers can be built by Nixpkgs, distributed via the cache, and declaratively deployed to any NixOS machine.
|
||||
|
||||
|
||||
- *Programming-language-specific infrastructure*
|
||||
|
||||
If Nixpkgs supports a given language then we require no additional infrastructure to support building and deploying that language. However, we might still host language-specific amenities on our utility server, such as generated documentation.
|
||||
|
||||
|
||||
- *Continuous-deployment services*
|
||||
|
||||
NixOS provides out-of-the-box services that we can use for continuous deployment, which we will cover in a later chapter.
|
||||
|
||||
|
||||
- *Cloud/Virtual development environments*
|
||||
|
||||
Nix's support for development shells (e.g. `nix develop`) will be our weapon of choice here.
|
||||
|
||||
|
||||
## Scope
|
||||
|
||||
So far I've explained NixOS in high-level terms, but you might prefer a more down-to-earth picture of the day-to-day requirements and responsibilities for a professional NixOS user.
|
||||
|
||||
To that end, here is a checklist that will summarize what you would need to understand in order to effectively introduce and support NixOS within an organization:
|
||||
|
||||
- Infrastructure setup
|
||||
- Continuous integration
|
||||
- Builders
|
||||
- Caching
|
||||
- Development
|
||||
- NixOS module system
|
||||
- Project organization
|
||||
- NixOS best practices
|
||||
- Quality controls
|
||||
- Testing
|
||||
- Running virtual machines
|
||||
- Automated testing
|
||||
- Deployment
|
||||
- Provisioning a new system
|
||||
- Upgrading a system
|
||||
- Dealing with restricted networks
|
||||
- System administration
|
||||
- Infrastructure as code
|
||||
- Disk management
|
||||
- Filesystem
|
||||
- Networking
|
||||
- Users and authentication
|
||||
- Limits and quotas
|
||||
- Security
|
||||
- System hardening
|
||||
- Patching dependencies
|
||||
- Diagnostics and Debugging
|
||||
- Nix failures
|
||||
- Test failures
|
||||
- Production failures
|
||||
- Useful references
|
||||
- Fielding inquiries
|
||||
- System settings
|
||||
- Licenses
|
||||
- Vulnerabilities
|
||||
- Non-NixOS Integrations
|
||||
- Images
|
||||
- Containers
|
||||
|
||||
This book will cover all of the above topics and more, although they will not necessarily be grouped or organized in that exact order.
|
||||
|
||||
---
|
||||
|
||||
**Previous:** [02. Motivation](02-motivation.md) · **Index:** [Table of Contents](../README.md) · **Next:** [04. Setup](04-setup.md)
|
||||
@@ -0,0 +1,329 @@
|
||||
# 04. Setup
|
||||
|
||||
> [!NOTE]
|
||||
> **Attribution:** Adapted from [*NixOS in Production*](https://github.com/Gabriella439/nixos-in-production) by Gabriella Gonzalez ([CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/)).
|
||||
> Support the author by purchasing the official edition on [Leanpub](https://leanpub.com/nixos-in-production).
|
||||
|
||||
---
|
||||
|
||||
I'd like you to be able to follow along with the examples in this book, so this chapter provides a quick setup guide to bootstrap from nothing to deploying a blank NixOS system that you can use for experimentation.
|
||||
|
||||
## Installing Nix
|
||||
|
||||
In order to follow along with this book you will need the following requirements:
|
||||
|
||||
- Nix version 2.18.1 or newer
|
||||
|
||||
- Flake support enabled
|
||||
|
||||
Specifically, you'll need to enable the following experimental features in your [Nix configuration file](https://nixos.org/manual/nix/stable/command-ref/conf-file.html):
|
||||
|
||||
```
|
||||
extra-experimental-features = nix-command flakes repl-flake
|
||||
```
|
||||
|
||||
You've likely already installed Nix if you're reading this book, but I'll still cover how to do this because I have a few tips to share that can help you author a more reliable installation script for your colleagues.
|
||||
|
||||
Needless to say, if you or any of your colleagues are using NixOS as your development operating system then you don't need to install Nix and you can skip to the [Running a NixOS Virtual Machine](#running-a-nixos-virtual-machine) section below.
|
||||
|
||||
### Default installation
|
||||
|
||||
If you go to the [download page for Nix](https://nixos.org/download.html) it will tell you to run something similar to this:
|
||||
|
||||
```bash
|
||||
$ sh <(curl --location https://nixos.org/nix/install)
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Throughout this book I'll use consistently long option names instead of short names (e.g. `--location` instead of `-L`), for two reasons:
|
||||
>
|
||||
> - Long option names are more self-documenting
|
||||
>
|
||||
> - Long option names are easier to remember
|
||||
>
|
||||
> For example, `tar --extract --file` is clearer and a better mnemonic than `tar xf`.
|
||||
>
|
||||
> You may freely use shorter option names if you prefer, though, but I still highly recommend using long option names at least for non-interactive scripts.
|
||||
|
||||
Depending on your platform the download instructions might also tell you to pass the `--daemon` or `--no-daemon` option to the installation script to specify a single-user or multi-user installation. For simplicity, the instructions in this chapter will omit the `--daemon` / `--no-daemon` flag, but keep in mind the following platform-specific advice:
|
||||
|
||||
- *On macOS the installer defaults to a multi-user Nix installation*
|
||||
|
||||
macOS doesn't even support a single-user Nix installation, so this is a good default.
|
||||
|
||||
|
||||
- *On Windows the installer defaults to a single-user Nix installation*
|
||||
|
||||
This default is also the recommended option.
|
||||
|
||||
|
||||
- *On Linux the installer defaults to a single-user Nix installation*
|
||||
|
||||
This is the one case where the default behavior is questionable. Multi-user Nix installations are typically better if your Linux distribution supports Systemd, so you should explicitly specify `--daemon` if you use `systemd`.
|
||||
|
||||
### Pinning the version
|
||||
|
||||
First, we will want to pin the version of Nix that you install if you're creating setup instructions for others to follow. For example, this book will be based on Nix version 2.18.1, and you can pin the Nix version like this:
|
||||
|
||||
```bash
|
||||
$ VERSION='2.18.1'
|
||||
$ URL="https://releases.nixos.org/nix/nix-${VERSION}/install"
|
||||
$ sh <(curl --location "${URL}")
|
||||
```
|
||||
|
||||
… and you can find the full set of available releases by visiting the [release file server](https://releases.nixos.org/?prefix=nix/).
|
||||
|
||||
> [!NOTE]
|
||||
> Feel free to use a Nix version newer than 2.18.1 if you want. The above example installation script only pins the version 2.18.1 because that's what happened to be the latest stable version at the time of this writing. That's also the Nix version that the examples from this book have been tested against.
|
||||
>
|
||||
> The only really important thing is that everyone within your organization uses the same version of Nix, if you want to minimize your support burden.
|
||||
|
||||
However, there are a few more options that the script accepts that we're going to make good use of, and we can list those options by supplying `--help` to the script:
|
||||
|
||||
```bash
|
||||
$ VERSION='2.18.1'
|
||||
$ URL="https://releases.nixos.org/nix/nix-${VERSION}/install"
|
||||
$ sh <(curl --location "${URL}") --help
|
||||
```
|
||||
|
||||
```
|
||||
Nix Installer [--daemon|--no-daemon] [--daemon-user-count INT] [--no-channel-add] [--no-modify-profile] [--nix-extra-conf-file FILE]
|
||||
Choose installation method.
|
||||
|
||||
--daemon: Installs and configures a background daemon that manages the store,
|
||||
providing multi-user support and better isolation for local builds.
|
||||
Both for security and reproducibility, this method is recommended if
|
||||
supported on your platform.
|
||||
See https://nixos.org/manual/nix/stable/installation/installing-binary.html#multi-user-installation
|
||||
|
||||
--no-daemon: Simple, single-user installation that does not require root and is
|
||||
trivial to uninstall.
|
||||
(default)
|
||||
|
||||
--no-channel-add: Don't add any channels. nixpkgs-unstable is installed by default.
|
||||
|
||||
--no-modify-profile: Don't modify the user profile to automatically load nix.
|
||||
|
||||
--daemon-user-count: Number of build users to create. Defaults to 32.
|
||||
|
||||
--nix-extra-conf-file: Path to nix.conf to prepend when installing /etc/nix/nix.conf
|
||||
|
||||
--tarball-url-prefix URL: Base URL to download the Nix tarball from.
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> You might wonder if you can use the `--tarball-url-prefix` option for distributing a custom build of Nix, but that's not what this option is for. You can only use this option to download Nix from a different location (e.g. an internal mirror), because the new download still has to match the same integrity check as the old download.
|
||||
>
|
||||
> Don't worry, though; there still is a way to distribute a custom build of Nix, and we'll cover that in a later chapter.
|
||||
|
||||
### Configuring the installation
|
||||
|
||||
The extra options of interest to us are:
|
||||
|
||||
- `--nix-extra-conf-file`
|
||||
|
||||
This lets you extend the installed `nix.conf` if you want to make sure that all users within your organization share the same settings.
|
||||
|
||||
|
||||
- `--no-channel-add`
|
||||
|
||||
You can (and should) enable this option within a professional organization to disable the preinstallation of any channels.
|
||||
|
||||
|
||||
These two options are crucial because we are going to use them to systematically replace Nix channels with flakes.
|
||||
|
||||
> [!WARNING]
|
||||
> Nix channels are a trap and I treat them as a legacy Nix feature poorly suited for professional development, despite how ingrained they are in the Nix ecosystem.
|
||||
>
|
||||
> The issue with channels is that they essentially introduce impurity into your builds by depending on the `NIX_PATH` and there aren't great solutions for enforcing that every Nix user or every machine within your organization has the exact same `NIX_PATH`.
|
||||
>
|
||||
> Moreover, Nix now supports flakes, which you can think of as a more modern alternative to channels. Familiarity with flakes is not a precondition to reading this book, though: I'll teach you what you need to know.
|
||||
|
||||
So what we're going to do is:
|
||||
|
||||
- *Disable channels by default*
|
||||
|
||||
Developers can still opt in to channels by installing them, but disabling channels by default will discourage people from contributing Nix code that depends on the `NIX_PATH`.
|
||||
|
||||
|
||||
- *Append the following setting to `nix.conf` to enable the use of flakes:*
|
||||
|
||||
```bash
|
||||
extra-experimental-features = nix-command flakes repl-flake
|
||||
```
|
||||
|
||||
|
||||
So the final installation script we'll end up with is:
|
||||
|
||||
```bash
|
||||
$ VERSION='2.18.1'
|
||||
$ URL="https://releases.nixos.org/nix/nix-${VERSION}/install"
|
||||
$ CONFIGURATION="
|
||||
extra-experimental-features = nix-command flakes repl-flake
|
||||
extra-trusted-users = ${USER}
|
||||
"
|
||||
$ sh <(curl --location "${URL}") \
|
||||
--no-channel-add \
|
||||
--nix-extra-conf-file <(<<< "${CONFIGURATION}")
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> The prior script only works if your shell is Bash or Zsh and all shell commands throughout this book assume the use of one of those two shells.
|
||||
>
|
||||
> For example, the above command uses support for process substitution (which is not available in a POSIX shell environment) because otherwise we'd have to create a temporary file to store the `CONFIGURATION` and clean up the temporary file afterwards (which is tricky to do 100% reliably). Process substitution is also more reliable than a temporary file because it happens entirely in memory and the intermediate result can't be accidentally deleted.
|
||||
|
||||
<a id="running-a-nixos-virtual-machine"></a>
|
||||
## Running a NixOS virtual machine
|
||||
|
||||
Now that you've installed Nix I'll show you how to launch a NixOS virtual machine (VM) so that you can easily test the examples throughout this book.
|
||||
|
||||
<a id="darwin-builder"></a>
|
||||
### macOS-specific instructions
|
||||
|
||||
If you are using macOS, then follow the instructions in the [Nixpkgs manual](https://nixos.org/manual/nixpkgs/stable/#sec-darwin-builder) to set up a local Linux builder. We'll need this builder to create other NixOS machines, since they require Linux build products.
|
||||
|
||||
In particular, you will need to leave that builder running in the background while following the remaining examples in this chapter. In other words, in one terminal window you will need to run:
|
||||
|
||||
```bash
|
||||
$ nix run 'nixpkgs#darwin.linux-builder'
|
||||
```
|
||||
|
||||
… and you will need that to be running whenever you need to build a NixOS system. However, you can shut down the builder when you're not using it by giving the builder the `shutdown now` command.
|
||||
|
||||
> [!WARNING]
|
||||
> The `nix run nixpkgs#darwin.linux-builder` command is not enough to set up Linux builds on macOS. Read and follow the full set of instructions from the Nixpkgs manual linked above.
|
||||
|
||||
If you are using Linux (including NixOS or the Windows Subsystem for Linux) you can skip to the next step.
|
||||
|
||||
### Platform-independent instructions
|
||||
|
||||
Run the following command to generate your first project:
|
||||
|
||||
```bash
|
||||
$ nix flake init --template 'github:Gabriella439/nixos-in-production/0.10#setup'
|
||||
```
|
||||
|
||||
… that will generate the following `flake.nix` file:
|
||||
|
||||
```nix
|
||||
{ inputs = {
|
||||
flake-utils.url = "github:numtide/flake-utils/v1.0.0";
|
||||
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/23.11";
|
||||
};
|
||||
|
||||
outputs = { flake-utils, nixpkgs, ... }:
|
||||
flake-utils.lib.eachDefaultSystem (system:
|
||||
let
|
||||
pkgs = nixpkgs.legacyPackages."${system}";
|
||||
|
||||
base = { lib, modulesPath, ... }: {
|
||||
imports = [ "${modulesPath}/virtualisation/qemu-vm.nix" ];
|
||||
|
||||
# https://github.com/utmapp/UTM/issues/2353
|
||||
networking.nameservers = lib.mkIf pkgs.stdenv.isDarwin [ "8.8.8.8" ];
|
||||
|
||||
virtualisation = {
|
||||
graphics = false;
|
||||
|
||||
host = { inherit pkgs; };
|
||||
};
|
||||
};
|
||||
|
||||
machine = nixpkgs.lib.nixosSystem {
|
||||
system = builtins.replaceStrings [ "darwin" ] [ "linux" ] system;
|
||||
|
||||
modules = [ base ./module.nix ];
|
||||
};
|
||||
|
||||
program = pkgs.writeShellScript "run-vm.sh" ''
|
||||
export NIX_DISK_IMAGE=$(mktemp -u -t nixosXXX.qcow2)
|
||||
|
||||
trap "rm -f $NIX_DISK_IMAGE" EXIT
|
||||
|
||||
${machine.config.system.build.vm}/bin/run-nixos-vm
|
||||
'';
|
||||
|
||||
in
|
||||
{ packages = { inherit machine; };
|
||||
|
||||
apps.default = {
|
||||
type = "app";
|
||||
|
||||
program = "${program}";
|
||||
};
|
||||
}
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
… and also the following `module.nix` file:
|
||||
|
||||
```nix
|
||||
# module.nix
|
||||
|
||||
{ services.getty.autologinUser = "root";
|
||||
}
|
||||
```
|
||||
|
||||
Then run this command within the same directory to run our test virtual machine:
|
||||
|
||||
```
|
||||
$ nix run
|
||||
warning: creating lock file '…/flake.lock'
|
||||
trace: warning: system.stateVersion is not set, defaulting to 23.11. …
|
||||
…
|
||||
|
||||
Run 'nixos-help' for the NixOS manual.
|
||||
|
||||
nixos login: root (automatic login)
|
||||
|
||||
|
||||
[root@nixos:~]#
|
||||
```
|
||||
|
||||
You can then shut down the virtual machine by entering `shutdown now`.
|
||||
|
||||
> [!NOTE]
|
||||
> If you're unable to shut down the machine gracefully for any reason you can shut down the machine non-gracefully by typing `Ctrl`-`a` + `c` to open the `qemu` prompt and then entering `quit` to exit.
|
||||
>
|
||||
> Also, don't worry about the `system.stateVersion` warning for now. We'll fix that later.
|
||||
|
||||
If you were able to successfully launch and shut down the virtual machine then you're ready to follow along with the remaining examples throughout this book. If you see an example in this book that begins with this line:
|
||||
|
||||
```nix
|
||||
# module.nix
|
||||
|
||||
…
|
||||
```
|
||||
|
||||
… then that means that I want you to save that example code to the `module.nix` file and then restart the virtual machine by running `nix run`.
|
||||
|
||||
For example, let's test that right now; save the following file to `module.nix`:
|
||||
|
||||
```nix
|
||||
# module.nix
|
||||
|
||||
{ services.getty.autologinUser = "root";
|
||||
|
||||
services.postgresql.enable = true;
|
||||
}
|
||||
```
|
||||
|
||||
… then start the virtual machine and log into the machine. As the `root` user, run:
|
||||
|
||||
```bash
|
||||
[root@nixos:~]# sudo --user postgres psql
|
||||
psql (14.5)
|
||||
Type "help" for help.
|
||||
|
||||
postgres=#
|
||||
```
|
||||
|
||||
… and now you should have command-line access to a `postgres` database.
|
||||
|
||||
The run script in the `flake.nix` file ensures that the virtual machine does not persist state in between runs so that you can safely experiment inside of the virtual machine without breaking upcoming examples.
|
||||
|
||||
---
|
||||
|
||||
**Previous:** [03. The Big Picture](03-big-picture.md) · **Index:** [Table of Contents](../README.md) · **Next:** [05. Web Server](05-web-server.md)
|
||||
@@ -0,0 +1,318 @@
|
||||
# 05. Web Server
|
||||
|
||||
> [!NOTE]
|
||||
> **Attribution:** Adapted from [*NixOS in Production*](https://github.com/Gabriella439/nixos-in-production) by Gabriella Gonzalez ([CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/)).
|
||||
> Support the author by purchasing the official edition on [Leanpub](https://leanpub.com/nixos-in-production).
|
||||
|
||||
---
|
||||
|
||||
Now that we can build and run a local NixOS virtual machine we can create our first toy web server. We will use this server throughout this book as the running example which will start off simple and slowly grow in maturity as we increase the realism of the example and build out the supporting infrastructure.
|
||||
|
||||
<a id="hello-world"></a>
|
||||
## Hello, world!
|
||||
|
||||
We'll begin from the template project from "Setting up your development environment". You can either begin from the previous chapter by running the following command (if you haven't done so already):
|
||||
|
||||
```bash
|
||||
$ nix flake init --template 'github:Gabriella439/nixos-in-production/0.10#setup'
|
||||
```
|
||||
|
||||
… or if you want to skip straight to the final result at the end of this chapter you can run:
|
||||
|
||||
```bash
|
||||
$ nix flake init --template 'github:Gabriella439/nixos-in-production/0.10#server'
|
||||
```
|
||||
|
||||
Let's modify `module.nix` to specify a machine that serves a simple static "Hello, world!" page on `http://localhost`:
|
||||
|
||||
```nix
|
||||
# module.nix
|
||||
|
||||
{ pkgs, ... }:
|
||||
|
||||
{ services = {
|
||||
getty.autologinUser = "root";
|
||||
|
||||
nginx = {
|
||||
enable = true;
|
||||
|
||||
virtualHosts.localhost.locations."/" = {
|
||||
index = "index.html";
|
||||
|
||||
root = pkgs.writeTextDir "index.html" ''
|
||||
<html>
|
||||
<body>
|
||||
Hello, world!
|
||||
</body>
|
||||
</html>
|
||||
'';
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
networking.firewall.allowedTCPPorts = [ 80 ];
|
||||
|
||||
virtualisation.forwardPorts = [
|
||||
{ from = "host"; guest.port = 80; host.port = 8080; }
|
||||
];
|
||||
|
||||
system.stateVersion = "23.11";
|
||||
}
|
||||
```
|
||||
|
||||
You can read the above code as saying:
|
||||
|
||||
- *Enable `nginx` which currently only listens on `localhost`*
|
||||
|
||||
In other words, `nginx` will only respond to requests addressed to `localhost` (e.g. `127.0.0.1`).
|
||||
|
||||
|
||||
- *Serve a static web page*
|
||||
|
||||
… which is a bare-bones "Hello, world!" HTML page.
|
||||
|
||||
|
||||
- *Open port 80 on the virtual machine's firewall*
|
||||
|
||||
… since that is the port that `nginx` will listen on by default until we create a certificate and enable TLS.
|
||||
|
||||
|
||||
- *Forward port 8080 on the "host" to port 80 on the "guest"*
|
||||
|
||||
The "guest" is the virtual machine and the "host" is your development machine.
|
||||
|
||||
|
||||
- *Allow the `root` user to log in with an empty password*
|
||||
|
||||
|
||||
- *Set the system's "state version" to 23.11*
|
||||
|
||||
> [!NOTE]
|
||||
> You always want to specify a system state version that matches the starting version of Nixpkgs for that machine and *never change it* afterwards. In other words, even if you upgrade Nixpkgs later on you would keep the state version the same.
|
||||
>
|
||||
> Nixpkgs uses the state version to migrate your NixOS system because in order to migrate your system each migration needs to know where your system started from.
|
||||
>
|
||||
> Two common mistakes NixOS users sometimes make are:
|
||||
>
|
||||
> - *updating the state version when they upgrade Nixpkgs*
|
||||
>
|
||||
> This will cause the machine to never be migrated because Nixpkgs will think that the machine was never deployed to an older version.
|
||||
>
|
||||
>
|
||||
> - *specifying a uniform state version across a fleet of NixOS machines*
|
||||
>
|
||||
> For example, you might have one NixOS machine in your data center that was first deployed using Nixpkgs 23.05 and another machine in your data center that was first deployed using Nixpkgs 23.11. If you try to change their state versions to match then one or the other might not upgrade correctly.
|
||||
|
||||
If you deploy that using `nix run` you can open the web page in your browser by visiting [`http://localhost:8080`](http://localhost:8080) which should display the following contents:
|
||||
|
||||
> Hello, world!
|
||||
|
||||
> [!WARNING]
|
||||
> In general I don't recommend testing things by hand like this. Remember the "master cue":
|
||||
>
|
||||
> > Every common build/test/deploy-related activity should be possible with at most a single command using Nix’s command line interface.
|
||||
>
|
||||
> In a later chapter we'll cover how to automate this sort of testing using NixOS's support for integration tests. These tests will also take care of starting up and tearing down the virtual machine for you so that you don't have to do that by hand either.
|
||||
|
||||
## DevOps
|
||||
|
||||
The previous example illustrates how NixOS promotes DevOps on a small scale. If the inline web page represents the software development half of the project (the "Dev") and the `nginx` configuration represents the operational half of the project (the "Ops") then we can in principle store both the "Dev" and the "Ops" halves of our project within the same file. As an extreme example, we can even template the web page with system configuration options!
|
||||
|
||||
```nix
|
||||
# module.nix
|
||||
|
||||
{ config, lib, pkgs, ... }:
|
||||
|
||||
{ services = {
|
||||
getty.autologinUser = "root";
|
||||
|
||||
nginx = {
|
||||
enable = true;
|
||||
|
||||
virtualHosts.localhost.locations."/" = {
|
||||
index = "index.html";
|
||||
|
||||
root = pkgs.writeTextDir "index.html" ''
|
||||
<html>
|
||||
<body>
|
||||
This server's firewall has the following open ports:
|
||||
|
||||
<ul>
|
||||
${
|
||||
let
|
||||
renderPort = port: "<li>${toString port}</li>\n";
|
||||
|
||||
in
|
||||
lib.concatMapStrings renderPort config.networking.firewall.allowedTCPPorts
|
||||
}
|
||||
</ul>
|
||||
</body>
|
||||
</html>
|
||||
'';
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
networking.firewall.allowedTCPPorts = [ 80 ];
|
||||
|
||||
virtualisation.forwardPorts = [
|
||||
{ from = "host"; guest.port = 80; host.port = 8080; }
|
||||
];
|
||||
|
||||
system.stateVersion = "23.11";
|
||||
}
|
||||
```
|
||||
|
||||
If you restart the machine and refresh [http://localhost:8080](http://localhost:8080) the page should now display:
|
||||
|
||||
> This server's firewall has the following open ports:
|
||||
>
|
||||
> - 80
|
||||
|
||||
> [!NOTE]
|
||||
> There are less roundabout ways to query our system's configuration that don't involve serving a web page. For example, using the same `flake.nix` file we can more directly query the open ports using:
|
||||
>
|
||||
> ```bash
|
||||
> $ nix eval '.#machine.config.networking.firewall.allowedTCPPorts'
|
||||
> [ 80 ]
|
||||
> ```
|
||||
|
||||
## TODO list
|
||||
|
||||
Now we're going to create the first prototype of a toy web application: a TODO list implemented entirely in client-side JavaScript (later on we'll add a backend service).
|
||||
|
||||
Create a subdirectory named `www` within your current directory:
|
||||
|
||||
```bash
|
||||
$ mkdir www
|
||||
```
|
||||
|
||||
… and then save a file named `index.html` with the following contents underneath that subdirectory:
|
||||
|
||||
```html
|
||||
<html>
|
||||
<body>
|
||||
<button id='add'>+</button>
|
||||
</body>
|
||||
<script>
|
||||
let add = document.getElementById('add');
|
||||
function newTask() {
|
||||
let subtract = document.createElement('button');
|
||||
subtract.textContent = "-";
|
||||
let input = document.createElement('input');
|
||||
input.setAttribute('type', 'text');
|
||||
let div = document.createElement('div');
|
||||
div.replaceChildren(subtract, input);
|
||||
function remove() {
|
||||
div.replaceChildren();
|
||||
div.remove();
|
||||
}
|
||||
subtract.addEventListener('click', remove);
|
||||
add.before(div);
|
||||
}
|
||||
add.addEventListener('click', newTask);
|
||||
</script>
|
||||
</html>
|
||||
```
|
||||
|
||||
In other words, the above file should be located at `www/index.html` relative to the directory containing your `module.nix` file.
|
||||
|
||||
Now save the following NixOS configuration to `module.nix`:
|
||||
|
||||
```nix
|
||||
# module.nix
|
||||
|
||||
{ services = {
|
||||
getty.autologinUser = "root";
|
||||
|
||||
nginx = {
|
||||
enable = true;
|
||||
|
||||
virtualHosts.localhost.locations."/" = {
|
||||
index = "index.html";
|
||||
|
||||
root = ./www;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
networking.firewall.allowedTCPPorts = [ 80 ];
|
||||
|
||||
virtualisation.forwardPorts = [
|
||||
{ from = "host"; guest.port = 80; host.port = 8080; }
|
||||
];
|
||||
|
||||
system.stateVersion = "23.11";
|
||||
}
|
||||
```
|
||||
|
||||
If you restart the virtual machine and refresh the web page you'll see a single `+` button:
|
||||
|
||||

|
||||
|
||||
Each time you click the `+` button it will add a TODO list item consisting of:
|
||||
|
||||
- A text entry field to record the TODO item
|
||||
|
||||
- A `-` button to delete the TODO item
|
||||
|
||||
|
||||
|
||||

|
||||
|
||||
> [!WARNING]
|
||||
> If you run into an error like:
|
||||
>
|
||||
> ```
|
||||
> error: getting status of '/nix/store/…-source/www': No such file or directory
|
||||
> ```
|
||||
>
|
||||
> … this can happen because you created the `./www` directory inside of a `git` repository. When you use flakes inside of a repository you need to explicitly add them and all files they depend on to the repository using:
|
||||
>
|
||||
> ```bash
|
||||
> $ git add ./www
|
||||
> ```
|
||||
>
|
||||
> Technically, the bare minimum you need to do is actually:
|
||||
>
|
||||
> ```bash
|
||||
> $ git add --intent-to-add ./www
|
||||
> ```
|
||||
>
|
||||
> … which comes in handy if you are not yet ready to commit the file.
|
||||
|
||||
## Passing through the filesystem
|
||||
|
||||
The previous NixOS configuration requires rebuilding and restarting the virtual machine every time we change the web page. If you try to change the `./www/index.html` file while the virtual machine is running you won't see any changes take effect.
|
||||
|
||||
However, we can pass through our local filesystem to the virtual machine so that we can easily test changes. To do so, add the following option to the configuration:
|
||||
|
||||
```nix
|
||||
virtualisation.sharedDirectories.www = {
|
||||
source = "$WWW";
|
||||
target = "/var/www";
|
||||
};
|
||||
```
|
||||
|
||||
… and change `module.nix` to reference `/var/www`, like this:
|
||||
|
||||
```nix
|
||||
virtualHosts.localhost.locations."/" = {
|
||||
index = "index.html";
|
||||
root = "/var/www";
|
||||
};
|
||||
```
|
||||
|
||||
Finally, restart the machine, except with a slightly modified version of our original `nix run` command:
|
||||
|
||||
```bash
|
||||
$ WWW="$PWD/www" nix run
|
||||
```
|
||||
|
||||
Now, we only need to refresh the page to view any changes we make to `index.html` and we no longer need to restart the virtual machine.
|
||||
|
||||
**Exercise**: Add a "TODO list" heading (i.e. `<h1>TODO list</h1>`)to the web page and refresh the page to confirm that your changes took effect.
|
||||
|
||||
---
|
||||
|
||||
**Previous:** [04. Setup](04-setup.md) · **Index:** [Table of Contents](../README.md) · **Next:** [06. Modules](06-modules.md)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 6.3 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 41 KiB |
Reference in new issue
Block a user