FAQ: Difference between revisions

From NixOS Wiki
imported>Makefu
Undo revision 128 by Makefu (talk)
imported>Makefu
import from nixos-users
Line 1: Line 1:
Frequently asked questions and common newcomer trouble should be put here so that we can point to this page instead of answering the same question over and over again.
Frequently asked questions and common newcomer trouble should be put here so that we can point to this page instead of answering the same question over and over again.


New questions should go to http://unix.stackexchange.com/questions/tagged/nixos
http://unix.stackexchange.com/questions/tagged/nixos can also be used for questions.


== Why is Nix written in C++ and Perl rather than a functional language like Haskell or OCaml, given the strong influence that functional programming has obviously had on Nix ==
== Why is Nix written in C++ rather than a functional language like Haskell or OCaml, given the strong influence that functional programming has obviously had on Nix ==


Mainly because Nix is intended to be lightweight, easy to learn and portable (zero dependencies).
Mainly because Nix is intended to be lightweight, easy to learn and portable (zero dependencies). Since 24. April 2017 thanks to [https://github.com/shlevy Shea Levy] and the [https://www.gofundme.com/htuafwrg/ crowdfunding of 54 community members], nix does not have Perl as dependency anymore.


== Using nix to install new software requires downloading the source from upstream and the source has moved and therefore the download doesn't work ==
== I installed a library but my compiler is not finding it. Why? ==


After some google search with [https://www.google.com/search?q=myfile-0.1.2.tar.gz+%22index+of%22 myfile-0.1.2.tar.gz "index of"] one usually can find the file and either:
With nix, only ''applications'' should be installed into profiles. Libraries are used using nix-shell. If you want to compile a piece of software that requires zlib and uses pkg-config to discover it, run <code>nix-shell -p pkgconfig zlib</code> to get into a shell with the appropriate environment variables set. In there, a configure script will work as expected.
* download it manually and copy into /tmp, then move that file into the store using:
  nix-prefetch-url file:///tmp/myfile-0.1.2.tar.gz # if the file is in the /tmp directory
* download it directly
  nix-prefetch-url "http://example.com/programs/foo/myfile-0.1.2.tar.gz"


== How to restart a systemd service? ==
This applies to other language environments too. In some cases the expressions to use are a bit different, e.g. because the interpreter needs to be wrapped to have some additional environment variables passed to it. The manual has [https://nixos.org/nixpkgs/manual/#chap-language-support a section] on the subject.


  systemctl restart unit
If you have a lot of dependencies, you may want to write a nix expression that includes your dependencies so that you can simply use <code>nix-shell</code> rather than writing out each dependency every time or keeping your development environment in your shell history. A minimal example looks like this:


A list of services can be found with:
<pre class="nix"># default.nix
with import &lt;nixpkgs&gt; {};
stdenv.mkDerivation {
    name = &quot;dev-environment&quot;; # Probably put a more meaningful name here
    buildInputs = [ pkgconfig zlib ];
}</pre>
=== Why does it work like that? ===


  systemctl list-units
This helps ensure purity of builds: on other distributions, the result of building a piece of software may depend on which other software you have installed. Nix attempts to avoid this to the greatest degree possible, which allows builds of a piece of software to be identical (in the ideal case) no matter where they're built, by requiring all dependencies to be declared.


== How to keep build-time dependencies around / be able to rebuild while being offline? ==
== How to keep build-time dependencies around / be able to rebuild while being offline? ==


configuration.nix:
<pre class="nix"># /etc/nixos/configuration.nix
   <nowiki>nix.extraOptions = ''
{ config, pkgs, lib, ... }:
{
   nix.extraOptions = ''
     gc-keep-outputs = true
     gc-keep-outputs = true
     gc-keep-derivations = true
     gc-keep-derivations = true
   '';</nowiki>
   '';
}</pre>
Check 'man configuration.nix' for these options. Rebuild for these options to take effect:


Check <code>man configuration.nix</code> for these options. Rebuild for these options to take effect:
<pre class="console">nixos-rebuild switch</pre>
  # nixos-rebuild switch
List all store paths that form the system closure and realise them:
List all store paths that form the system closure and realise them:
  $ nix-store -qR $(nix-instantiate /etc/nixos/nixos -A system) | xargs nix-store -r
 
  warning: you did not specify `--add-root'; the result might be removed by the garbage collector
<pre class="console">nix-store -qR $(nix-instantiate /etc/nixos/nixos -A system) | xargs nix-store -r</pre>
  ...
<pre class="shell">warning: you did not specify `--add-root'; the result might be removed by the garbage collector</pre>
  <build output and list of successfully realised paths>
<pre class="shell"></pre>
<pre class="shell">&lt;build output and list of successfully realised paths&gt;</pre>
Repeat for your user and further profiles:
Repeat for your user and further profiles:
  $ nix-store -qR ~/.nix-profile |xargs nix-store -r


The warning can be ignored for profiles that are listed/linked in /nix/var/nix/profiles/ or one of its subdirectories.
<pre class="console">nix-store -qR ~/.nix-profile |xargs nix-store -r</pre>
The warning can be ignored for profiles that are listed/linked in ''/nix/var/nix/profiles/'' or one of its subdirectories.


Consult man pages of nix-store and nix-instantiate for further information.
Consult man pages of nix-store and nix-instantiate for further information.


== How to add a custom udev rule in nixos? ==
== Why &lt;hash&gt;-&lt;name&gt; instead of &lt;name&gt;-&lt;hash&gt;? ==


Add something like this to your <code>/etc/nixos/configuration.nix</code> file:
For the rare cases where we have to dig into the /nix/store it is more practical to keep in mind the first few letters at the beginning than finding a package by name. In addition, the hash is printed by Nix commands. If you still wonder why, run <code>ls -1 /nix/store | sort -R -t - -k 2 | less</code> in your shell.
<pre>
 
  services.udev.extraRules = ''
This is what might happen if you don't garbage collect frequently, or if you are testing compilation variants:
    ATTRS{idVendor}=="0665", ATTRS{idProduct}=="5161", MODE="666", SYMLINK+="hidraw_protecthome"
 
<pre class="shell">q0yi2nr8i60gm2zap46ryysydd2nhzhp-automake-1.11.1/
vbi4vwwidvd6kklq2kc0kx3nniwa3acl-automake-1.11.1/
wjgzir57hcbzrq3mcgxiwkyiqss3r4aq-automake-1.11.1/
1ch5549xnck37gg2w5fh1jgk6lkpq5mc-nixos-build-vms/
4cmjlxknzlvcdmfwj0ih0ggqsj5q73hb-nixos-build-vms/
7fv4kwi5wwwzd11ili3qwg28xrj8rxw2-nixos-build-vms/
8jij13smq9kdlqv96hm7y8xmbh2c54iy-nixos-build-vms/
j714mv53xi2j4ab4g2i08knqr137fd6l-nixos-build-vms/
xvs7y09jf7j48p6l0p87iypgpq470jqw-nixos-build-vms/</pre>
== I've updated my channel and something is broken, how can I rollback to an earlier channel? ==
 
View the available generations of your channel:
 
<pre class="console">nix-env --list-generations -p /nix/var/nix/profiles/per-user/root/channels</pre>
<pre class="shell">18  2014-04-17 09:16:28
19  2014-06-13 10:31:24
20  2014-08-12 19:09:20  (current)</pre>
To rollback to the previous generation:
 
<pre class="console">nix-env --rollback -p /nix/var/nix/profiles/per-user/root/channels</pre>
<pre class="shell">switching from generation 20 to 19</pre>
To switch to a particular generation:
 
<pre class="console">nix-env --switch-generation 18 -p /nix/var/nix/profiles/per-user/root/channels</pre>
<pre class="shell">switching from generation 20 to 18</pre>
== I'm working on a new package, how can I build it without adding it to nixpkgs? ==
 
<pre class="console">nix-build -E 'with import &lt;nixpkgs&gt; { }; callPackage ./mypackage.nix { }'</pre>
You can replace callPackage with callPackage_i686 to build the 32-bit version of your package on a 64-bit system if you want to test that.
 
== How can I compile a package with debugging symbols included? ==
 
To build a package with -O0 and -g, and without stripping debug symbols use:
 
<pre class="console">nix-build -E 'with import &lt;nixpkgs&gt; { }; enableDebugging fooPackage'</pre>
== How can I force a rebuild from source even without modifying the nix expression? ==
 
As root you can run nix-build with the --check flag:
 
<pre class="console">sudo nix-build --check -A ncdu</pre>
== How can I manage software with nix-env like with configuration.nix? ==
 
There are many ways, one is the following:
 
<ol style="list-style-type: decimal;">
<li><p>Create a meta package called ''userPackages'' your ''~/.config/nixpkgs/config.nix'' file with the packages you would like to have in your environment:</p>
<pre class="nix">  with (import &lt;nixpkgs&gt; {});
  {
packageOverrides = pkgs: with pkgs; {
userPackages = buildEnv {
  inherit ((import &lt;nixpkgs/nixos&gt; {}).config.system.path)
    pathsToLink ignoreCollisions postBuild;
  extraOutputsToInstall = [ &quot;man&quot; ];
  name = &quot;user-packages&quot;;
  paths = [ vim git wget ];
};
  }</pre></li>
<li><p>Install all specified packages using this command:</p>
<pre class="console">nix-env -iA userPackages -f '&lt;nixpkgs&gt;'</pre></li></ol>
 
Now you can add and remove packages from the paths list and rerun nix-env to update your user local packages.
 
== I've downloaded a binary, but I can't run it, what can I do? ==
 
It probably just needs to know where to find the libraries it needs. You can use [https://nixos.org/patchelf.html patchelf] to set the library path and dynamic linker appropriately:
 
<pre class="nix"># mybinaryprogram.nix
with import &lt;nixpkgs&gt; {}; with xlibs;
stdenv.mkDerivation rec {
  name = &quot;somename&quot;;
  buildInputs = [ makeWrapper ];
  buildPhase = &quot;true&quot;;
  libPath = lib.makeLibraryPath [ libXrandr libXinerama libXcursor ];
  unpackPhase = &quot;true&quot;;
  installPhase = ''
    mkdir -p $out/bin
    cp ${./mybinaryprogram} $out/bin/mybinaryprogram
    patchelf \
    --set-interpreter &quot;$(&lt; &quot;$NIX_CC/nix-support/dynamic-linker&quot;)&quot; \
    --set-rpath &quot;${libPath}&quot; \
    $out/bin/mybinaryprogram
   '';
   '';
</pre>
}</pre>
This can be built with:
 
<pre class="console">nix-build mybinaryprogram.nix</pre>
And run with:
 
<pre class="console">./result/bin/mybinaryprogram</pre>
Another possibility is using a FHS-compatible Sandbox with [https://nixos.org/nixpkgs/manual/#sec-fhs-environments buildFHSUserEnv]


== Why <hash>-<name> instead of <name>-<hash>? ==
<pre class="nix"># fhsUser.nix
{ pkgs ? import &lt;nixpkgs&gt; {} }:
(pkgs.buildFHSUserEnv {
  name = &quot;example-env&quot;;
  targetPkgs = pkgs: with pkgs; [
    coreutils
  ];
  multiPkgs = pkgs: with pkgs; [
    zlib
    xorg.libXxf86vm
    curl
    openal
    openssl_1_0_2
    xorg.libXext
    xorg.libX11
    xorg.libXrandr
    mesa_glu
  ];
  runScript = &quot;bash&quot;;
}).env</pre>
the sandbox can be entered with


For the rare cases where we have to dig into the /nix/store it is more practical to keep in mind the first few letters at the beginning than finding a package by name.  In addition, the hash is printed by Nix commands. If you still wonder why, run "<code>ls -1 /nix/store | sort -R -t - -k 2 | less</code>" in your shell.
<pre class="console">nix-shell fhsUser.nix</pre>
== What are channels and how they get updated? ==


This is what might happen if you don't garbage collect frequently, or if you are testing compilation variants:
[https://github.com/NixOS/nixpkgs Nixpkgs] is the git repository containing all packages and NixOS modules/expressions. Installing packages directly from Nixpkgs master branch is possible but a bit risky as git commits are merged into master before being heavily tested. That's where channels are useful.


  q0yi2nr8i60gm2zap46ryysydd2nhzhp-automake-1.11.1/
A &quot;channel&quot; is a name for the latest &quot;verified&quot; git commits in Nixpkgs. Each channel has a different definition of what &quot;verified&quot; means. Each time a new git commit is verified, the channel declaring this verification gets updated. Contrary to an user of the git master branch, a channel user will benefit both from verified commits and binary packages from the binary cache.
  vbi4vwwidvd6kklq2kc0kx3nniwa3acl-automake-1.11.1/
  wjgzir57hcbzrq3mcgxiwkyiqss3r4aq-automake-1.11.1/
  1ch5549xnck37gg2w5fh1jgk6lkpq5mc-nixos-build-vms/
  4cmjlxknzlvcdmfwj0ih0ggqsj5q73hb-nixos-build-vms/
  7fv4kwi5wwwzd11ili3qwg28xrj8rxw2-nixos-build-vms/
  8jij13smq9kdlqv96hm7y8xmbh2c54iy-nixos-build-vms/
  j714mv53xi2j4ab4g2i08knqr137fd6l-nixos-build-vms/
  xvs7y09jf7j48p6l0p87iypgpq470jqw-nixos-build-vms/


== Error: unable to check <nowiki>`https://nixos.org/channels/nixpkgs-unstable`</nowiki> ==
Channels are reified as git branches in the [https://github.com/NixOS/nixpkgs-channels nixpkgs-channels repository] and as disk images in the [https://nixos.org/channels/ channels webpage]. There are several channels, each with its own use case and verification phase:


'''Note: this problem appears to have already been fixed as of Nov 2014.'''
* '''nixos-unstable'''
* '''description''' Use this when you want the latest package and module versions while still benefiting from the binary cache. You can use this channel on non-NixOS systems. This channel corresponds to NixOS’s main development branch, and may thus see radical changes between channel updates. This channel is not recommended for production systems.
* '''definition''' this channel is updated depending on [https://github.com/NixOS/nixpkgs/blob/master/pkgs/top-level/release.nix release.nix] and [https://github.com/NixOS/nixpkgs/blob/master/pkgs/top-level/release-lib.nix release-lib.nix]
* '''nixos-unstable-small'''
* '''description''' This channel is identical to <code>nixos-unstable</code> described above, except that this channel contains fewer binary packages. This means the channel gets updated faster than <code>nixos-unstable</code> (for instance, when a critical security patch is committed to NixOS’s source tree). However, the binary cache may contain less binary packages and thus using this channel may require building more packages from source than <code>nixos-unstable</code>. This channel is mostly intended for server environments and as such contains few GUI applications.
* '''definition''' this channel is updated depending on [https://github.com/NixOS/nixpkgs/blob/master/pkgs/top-level/release-small.nix release-small.nix] and [https://github.com/NixOS/nixpkgs/blob/master/pkgs/top-level/release-lib.nix release-lib.nix]
* '''nixos-YY.MM''' (where '''YY''' is a 2-digit year and '''MM''' is a 2-digit month, such as [https://nixos.org/channels/nixos-15.09/ ''nixos-17.03''])
* '''description''' These channels are called '''stable''' and only get conservative bug fixes and package upgrades. For instance, a channel update may cause the Linux kernel on your system to be upgraded from 3.4.66 to 3.4.67 (a minor bug fix), but not from 3.4.x to 3.11.x (a major change that has the potential to break things). Stable channels are generally maintained until the next stable branch is created.
* '''definition''' this channel is updated depending on [https://github.com/NixOS/nixpkgs/blob/master/pkgs/top-level/release.nix release.nix] and [https://github.com/NixOS/nixpkgs/blob/master/pkgs/top-level/release-lib.nix release-lib.nix]
* '''nixos-YY.MM-small''' (where '''YY''' is a 2-digit year and '''MM''' is a 2-digit month, such as [https://nixos.org/channels/nixos-15.09-small/ nixos-15.09-small])
* '''description''' The difference between <code>nixos-YY.MM-small</code> and <code>nixos-YY.MM</code> is the name as the one between <code>nixos-unstable-small</code> and <code>nixos-unstable</code> (see above)


If you get an error like this:
Channel update works as follows:
<nowiki>
/home/user/.nix-profile/bin/nix-channel: unable to check `https://nixos.org/channels/nixpkgs-unstable'
</nowiki>


It's because of the https protocol: change the protocol to be http. For more information see https://github.com/NixOS/nixpkgs/pull/2688
# Each channel has a particular job at '''hydra.nixos.org''' which must succeed:


Another possible cause for this behaviour is a misconfigured shell profile. During installation nix adds the line
* For NixOS: the trunk-combined [http://hydra.nixos.org/job/nixos/trunk-combined/tested tested] job, which contains some automated NixOS tests.
  if [ -e /home/<user>/.nix-profile/etc/profile.d/nix.sh ]; then . /home/<user>/.nix-profile/etc/profile.d/nix.sh; fi
* For nixos-small: the unstable-small [http://hydra.nixos.org/job/nixos/unstable-small/tested tested] job.
to ''~/.profile''.
* For nixpkgs: the trunk [http://hydra.nixos.org/job/nixpkgs/trunk/unstable unstable] job, which contains some critical release packages.
If your shell does not source this file, add the line to your shell configuration (e.g. to .zshrc).


== I've updated my channel and something is broken, how can I rollback to an earlier channel? ==
<ol start="2" style="list-style-type: decimal;">
<li>Once the job succeeds at a particular nixpkgs commit, '''cache.nixos.org''' will download binaries from '''hydra.nixos.org'''.</li>
<li>Once the above download completes, the channel updates.</li></ol>


View the available generations of your channel:
You can checkout the nixpkgs git and reset it to a particular commit of a channel. This will not affect your access to the binary cache.
<pre>
  $ nix-env --list-generations -p /nix/var/nix/profiles/per-user/root/channels
    18  2014-04-17 09:16:28
    19  2014-06-13 10:31:24
    20  2014-08-12 19:09:20  (current)
</pre>


To rollback to the previous generation:
== How do I know where's nixpkgs channel located and at which commit? ==


<pre>
First <code>echo $NIX_PATH</code> to see where nix looks for the expressions. Note that nix-env uses ''~/.nix-defexpr'' regardless of ''$NIX_PATH''.
  $ nix-env --rollback -p /nix/var/nix/profiles/per-user/root/channels
  switching from generation 20 to 19
</pre>


To switch to a particular generation:
If you want to know where <nixpkgs> is located:


<pre>
<pre class="console">nix-instantiate --find-file nixpkgs</pre>
  $ nix-env --switch-generation 18 -p /nix/var/nix/profiles/per-user/root/channels
To know the commit, open the .version-suffix file in the nixpkgs location. The hash after the dot is the git commit.
  switching from generation 20 to 18
</pre>


== I'm working on a new package, how can I build it without adding it to nixpkgs? ==
== An error occurs while fetching sources from an url, how do I fix it? ==


<pre>
First try to update the local nixpkgs expressions with <code>nix-channel --update</code> (these describe where to download sources from and how to build them). Try your build again and the url might have already been correctly updated for the package in question. You can also subscribe the unstable channel (which includes the most up-to-date expressions) with <code>nix-channel --add http://nixos.org/channels/nixpkgs-unstable</code>, update and try the build again.
  $ nix-build -E 'with import <nixpkgs> { }; callPackage ./mypackage.nix { }'
</pre>


You can replace callPackage with callPackage_i686 to build the 32-bit version of your package on a 64-bit system if you want to test that.
If that fails you can update the url in the nix expression yourself. [https://nixos.org/wiki/FAQ#How_do_I_know_where.27s_nixpkgs_channel_located_and_at_which_commit.3F Navigate to your channel's expressions] and find the package in one of the subdirectories. Edit the respective ''default.nix'' file by altering the ''url'' and ''sha256''. You can use <code>nix-prefetch-url url</code> to get the SHA-256 hash of source distributions.


If the shell complains that you do not have write privileges for the file system, you will have to enable them.


== How can I compile a package with debugging symbols included? ==
start a new shell with a private mount namespace (Linux-only)


To build a package with -O0 and -g, and without stripping debug symbols use:
<pre class="console">sudo unshare -m bash</pre>
remount the filesystem with write privileges (as root)


<pre>
<pre class="console">mount -o remount,rw /nix/store</pre>
  $ nix-build -E 'with import <nixpkgs> { }; enableDebugging fooPackage'
update the file
</pre>


== How can I force a rebuild from source even without modifying the nix expression? ==
<pre class="console">nano &lt;PATH_TO_PACKAGE&gt;/default.nix</pre>
exit to shell where /nix/store is still mounted read-only


As root you can run nix-build with the --check flag:
<pre class="console">exit</pre>
Be sure to [https://github.com/NixOS/nixpkgs/issues report the incorrect url] or [https://github.com/NixOS/nixpkgs/pulls fix it yourself].


<pre>
== How do I know the sha256 to use with fetchgit/fetchsvn/fetchbzr/fetchcvs? ==
  /root/nixpkgs $ nix-build --check -A ncdu
</pre>


== How can I manage software with nix-env like with configuration.nix? ==
Install <code>nix-prefetch-scripts</code> and use the corresponding nix prefetch helper.


There are many ways, one is the following:
For instance to get the checksum of a git repository use:


1) Create your <code>packages.nix</code> file with the packages you would like to have in your environment:
<pre class="console">nix-prefetch-git https://git.zx2c4.com/password-store</pre>
== Should I use http://hydra.nixos.org/ as a binary cache? ==


<pre>
Short answer: no.
  with (import <nixpkgs> {});
  { inherit pkg1 pkg2 ....; }
</pre>


2) Install all of them with <code>nix-env -f packages.nix -i</code>
http://cache.nixos.org is hosted on AWS S3, so it is fast and efficient, but it only contains binaries for nix channels (''nixos-unstable'', ''nixpkgs-unstable'', and some stable channels too).


With this approach, you can also install only certain packages by attribute name like this:
So, if the channel is way behind, you may see recommendations to add http://hydra.nixos.org/ as a binary cache, as it contains all recent builds, including ones not pushed to channels.


<code>$ nix-env -f packages.nix -iA pkg1</code>
Unfortunately, due to poor caching, http://hydra.nixos.org/ needs to calculate what is available ''every time'' you ask about substitutes, so using it regularly as a cache will slow down the build machines.


3) Install all the packages, and remove everything else by using the --remove-all (-r) switch
Thus, the recommended configuration is to '''not''' put http://hydra.nixos.org/ in any config file or automated script. But if you are working on nixpkgs master, then the binary cache provided by Hydra can be very helpful. In such a case, you can add the Hydra cache to the trusted binary caches in nix.conf or configuration.nix, restart the Nix daemon, and use <code>--option extra-binary-caches http://hydra.nixos.org/</code> in whatever commands are convenient.


<code>$ nix-env -f packages.nix -ir</code>
== I'm trying to install NixOS but my Wifi isn't working and I don't have an ethernet port ==


== I've downloaded a binary, but I can't run it, what can I do? ==
Most phones will allow you to share your Wifi connection over USB. On Android you can enable this setting via ''Settings'' &gt; ''Wireless &amp; Networks'' / More ... &gt; ''Tethering &amp; portable hotspot'' &gt; ''USB tethering''. This should be enough to allow you to install NixOS, and then fix your Wifi. iPhones only let you tether using your data connection rather than WiFi.


It probably just needs to know where to find the libraries it needs. You can write a simpler wrapper which sets LD_LIBRARY_PATH appropriately and installs it:
== How can I disable the binary cache and build everything locally? ==


mybinaryprogram.nix:
Set the binary caches to an empty list: <code>nix.binaryCaches = [];</code> in _configuration.nix or pass ad-hoc <code>--option binary-caches &quot;&quot;</code> as parameter to nix-build or its wrappers.
<pre>
  with import <nixpkgs> {}; with xlibs;
 
  stdenv.mkDerivation rec {
      name = "somename";
      buildInputs = [ makeWrapper ];
 
      buildPhase = "true";
 
      libPath = lib.makeLibraryPath [ libXrandr libXinerama libXcursor ];
 
      unpackPhase = "true";
 
      installPhase = ''
        mkdir -p $out/bin
        cp ${./mybinaryprogram} $out/bin/mybinaryprogram
        wrapProgram $out/bin/mybinaryprogram \
          --prefix LD_LIBRARY_PATH : "${libPath}"
      '';
  }
</pre>


This can be built with:
This is also useful to make simple configuration changes in NixOS (ex.: network related), when no network connectivity is available:


  $ nix-build mybinaryprogram.nix
<pre class="console">nixos-rebuild switch --option binary-caches &quot;&quot;</pre>
== How do I enable chrooted builds on non-NixOS? ==


And run with:
Two options have to be added to make chrooted builds work on Nix, ''build-use-chroot'' and ''build-chroot-dirs'':


  $ ./result/bin/mybinaryprogram
<pre class="nix"># /etc/nix/nix.conf
build-use-chroot = true
build-chroot-dirs = $(nix-store -qR $(nix-build '&lt;nixpkgs&gt;' -A bash) | xargs echo /bin/sh=$(nix-build '&lt;nixpkgs&gt;' -A bash)/bin/bash)</pre>
On NixOS set the following in ''configuration.nix'':


== What are channels and how they get updated? ==
<pre class="nix">nix.extraOptions = ''
  build-use-sandbox = true
'';</pre>
== I cannot find $package when running <code>nix-env -qaP</code> even with channels configured ==


[https://github.com/NixOS/nixpkgs Nixpkgs] is the repository containing all packages and nixos modules/expressions.
Not all packages are listed. Packages may not be listed because: - the package is unfree, like e.g. ''unrar'' and ''teamspeak_client''; - the package is part of an attribute set and <code>nix-env</code> doesn't recurse into this set (see ''pkgs.recurseIntoAttrs'')


A "channel" consists of a copy of the nixpkgs repository at a particular commit, and a url to the binary cache. The channel has no information about which binaries are available; it's just a copy of nixpkgs. When you install software, nix will ask the binary cache for that nix store path in order to download the actual binaries.
== How can I install a proprietary or unfree package? ==


Available nixos.org channels are: <tt>nixpkgs-unstable</tt>, <tt>nixos-unstable</tt>, <tt>nixos-<stable></tt> and <tt>nixos-<stable>-small</tt>, where <tt><stable></tt> refers to a stable version. You can see these channels at https://nixos.org/channels/, and find more detailed information at https://nixos.org/nixos/manual/index.html#sec-upgrading. Naturally, the <tt>-<stable></tt> channels track the related stable branch, while <tt>-unstable</tt> channels track the master branch.
If you want to install an unfree package as a user, then you need to enable it in ''~/.nixpkgs/config.nix'':


Channel update works as follows:
<pre class="nix">{
  ...
  allowUnfree = true;
}</pre>
If you want to enable unfree packages system-wide, then set in your <code>/etc/nixos/configuration.nix</code>:


# Each channel has a particular job at <tt>hydra.nixos.org</tt> which must succeed:
<pre class="nix">{
## For nixos: the trunk-combined [http://hydra.nixos.org/job/nixos/trunk-combined/tested "tested"] job, which contains some automated nixos tests.
  ...
## For nixos-small: the unstable-small [http://hydra.nixos.org/job/nixos/unstable-small/tested "tested"] job.
  nixpkgs.config.allowUnfree = true;
## For nixpkgs: the trunk [http://hydra.nixos.org/job/nixpkgs/trunk/unstable "unstable"] job, which contains some critical release packages.
}</pre>
# Once the job succeeds at a particular nixpkgs commit, <tt>cache.nixos.org</tt> will download binaries from <tt>hydra.nixos.org</tt>.
For temporary allowing unfree packages you can set the environment variable ''NIXPKGS_ALLOW_UNFREE'', e.g.
# Once the above download completes, the channel updates.


You can also use nixos-unstable on non-nixos. Remember that the channel is just a copy of nixpkgs and nix will ask the binary cache for a particular hash.
<pre class="console">NIXPKGS_ALLOW_UNFREE=1 nix-env</pre>
== How can I install a package from unstable while remaining on the stable channel? ==


You can also checkout the nixpkgs git and reset it to a particular commit of a channel. This will not affect your access to the binary cache.
It is possible to have multiple nix-channels simultaneously. To add the unstable channel with the specifier ''unstable'',


== How do I know where's nixpkgs channel located and at which commit? ==
<pre class="console">sudo nix-channel --add https://nixos.org/channels/nixos-unstable unstable</pre>
After updating the channel


First <code>echo $NIX_PATH</code> to see where nix looks for the expressions. Note that nix-env uses ~/.nix-defexpr regardless of $NIX_PATH.
<pre class="console">sudo nix-channel --update unstable</pre>
queries via <code>nix-env</code> (or <code>nox</code>) will show packages from both ''stable'' and ''unstable''. Use this to install unstable packages into your user environment. The following snippet shows how this can be done in ''configuration.nix''.


If you want to know where <nixpkgs> is located: <code>nix-instantiate --find-file nixpkgs</code>
<pre class="nix">{ config, pkgs, ... }:
let
  unstable = import &lt;nixos-unstable&gt; {};
in {
  environment.systemPackages = [ unstable.PACKAGE_NAME ];
}</pre>
= What is the origin of the name <code>Nix</code> =


To know the commit, open the .version-suffix file in the nixpkgs location. The hash after the dot is the git commit.
<blockquote>The name <code>Nix</code> is derived from the Dutch word ''niks'', meaning ''nothing'';build actions do not see anything that has not been explicitly declared as an input &gt; [https://pdfs.semanticscholar.org/5fd8/8f89bd8738816e62808a1b7fb12d3ab14a2f.pdf Nix: A Safe and Policy-Free System for Software Deployment, page 2]
</blockquote>

Revision as of 16:40, 21 August 2017

Frequently asked questions and common newcomer trouble should be put here so that we can point to this page instead of answering the same question over and over again.

http://unix.stackexchange.com/questions/tagged/nixos can also be used for questions.

Why is Nix written in C++ rather than a functional language like Haskell or OCaml, given the strong influence that functional programming has obviously had on Nix

Mainly because Nix is intended to be lightweight, easy to learn and portable (zero dependencies). Since 24. April 2017 thanks to Shea Levy and the crowdfunding of 54 community members, nix does not have Perl as dependency anymore.

I installed a library but my compiler is not finding it. Why?

With nix, only applications should be installed into profiles. Libraries are used using nix-shell. If you want to compile a piece of software that requires zlib and uses pkg-config to discover it, run nix-shell -p pkgconfig zlib to get into a shell with the appropriate environment variables set. In there, a configure script will work as expected.

This applies to other language environments too. In some cases the expressions to use are a bit different, e.g. because the interpreter needs to be wrapped to have some additional environment variables passed to it. The manual has a section on the subject.

If you have a lot of dependencies, you may want to write a nix expression that includes your dependencies so that you can simply use nix-shell rather than writing out each dependency every time or keeping your development environment in your shell history. A minimal example looks like this:

# default.nix
with import <nixpkgs> {};
stdenv.mkDerivation {
    name = "dev-environment"; # Probably put a more meaningful name here
    buildInputs = [ pkgconfig zlib ];
}

Why does it work like that?

This helps ensure purity of builds: on other distributions, the result of building a piece of software may depend on which other software you have installed. Nix attempts to avoid this to the greatest degree possible, which allows builds of a piece of software to be identical (in the ideal case) no matter where they're built, by requiring all dependencies to be declared.

How to keep build-time dependencies around / be able to rebuild while being offline?

# /etc/nixos/configuration.nix
{ config, pkgs, lib, ... }:
{
  nix.extraOptions = ''
    gc-keep-outputs = true
    gc-keep-derivations = true
  '';
}

Check 'man configuration.nix' for these options. Rebuild for these options to take effect:

nixos-rebuild switch

List all store paths that form the system closure and realise them:

nix-store -qR $(nix-instantiate /etc/nixos/nixos -A system) | xargs nix-store -r
warning: you did not specify `--add-root'; the result might be removed by the garbage collector

<build output and list of successfully realised paths>

Repeat for your user and further profiles:

nix-store -qR ~/.nix-profile |xargs nix-store -r

The warning can be ignored for profiles that are listed/linked in /nix/var/nix/profiles/ or one of its subdirectories.

Consult man pages of nix-store and nix-instantiate for further information.

Why <hash>-<name> instead of <name>-<hash>?

For the rare cases where we have to dig into the /nix/store it is more practical to keep in mind the first few letters at the beginning than finding a package by name. In addition, the hash is printed by Nix commands. If you still wonder why, run ls -1 /nix/store | sort -R -t - -k 2 | less in your shell.

This is what might happen if you don't garbage collect frequently, or if you are testing compilation variants:

q0yi2nr8i60gm2zap46ryysydd2nhzhp-automake-1.11.1/
vbi4vwwidvd6kklq2kc0kx3nniwa3acl-automake-1.11.1/
wjgzir57hcbzrq3mcgxiwkyiqss3r4aq-automake-1.11.1/
1ch5549xnck37gg2w5fh1jgk6lkpq5mc-nixos-build-vms/
4cmjlxknzlvcdmfwj0ih0ggqsj5q73hb-nixos-build-vms/
7fv4kwi5wwwzd11ili3qwg28xrj8rxw2-nixos-build-vms/
8jij13smq9kdlqv96hm7y8xmbh2c54iy-nixos-build-vms/
j714mv53xi2j4ab4g2i08knqr137fd6l-nixos-build-vms/
xvs7y09jf7j48p6l0p87iypgpq470jqw-nixos-build-vms/

I've updated my channel and something is broken, how can I rollback to an earlier channel?

View the available generations of your channel:

nix-env --list-generations -p /nix/var/nix/profiles/per-user/root/channels
18   2014-04-17 09:16:28
19   2014-06-13 10:31:24 
20   2014-08-12 19:09:20   (current)

To rollback to the previous generation:

nix-env --rollback -p /nix/var/nix/profiles/per-user/root/channels
switching from generation 20 to 19

To switch to a particular generation:

nix-env --switch-generation 18 -p /nix/var/nix/profiles/per-user/root/channels
switching from generation 20 to 18

I'm working on a new package, how can I build it without adding it to nixpkgs?

nix-build -E 'with import <nixpkgs> { }; callPackage ./mypackage.nix { }'

You can replace callPackage with callPackage_i686 to build the 32-bit version of your package on a 64-bit system if you want to test that.

How can I compile a package with debugging symbols included?

To build a package with -O0 and -g, and without stripping debug symbols use:

nix-build -E 'with import <nixpkgs> { }; enableDebugging fooPackage'

How can I force a rebuild from source even without modifying the nix expression?

As root you can run nix-build with the --check flag:

sudo nix-build --check -A ncdu

How can I manage software with nix-env like with configuration.nix?

There are many ways, one is the following:

  1. Create a meta package called userPackages your ~/.config/nixpkgs/config.nix file with the packages you would like to have in your environment:

      with (import <nixpkgs> {});
      {
    packageOverrides = pkgs: with pkgs; {
     userPackages = buildEnv {
      inherit ((import <nixpkgs/nixos> {}).config.system.path)
        pathsToLink ignoreCollisions postBuild;
      extraOutputsToInstall = [ "man" ];
      name = "user-packages";
      paths = [ vim git wget ];
    };
      }
  2. Install all specified packages using this command:

    nix-env -iA userPackages -f '<nixpkgs>'

Now you can add and remove packages from the paths list and rerun nix-env to update your user local packages.

I've downloaded a binary, but I can't run it, what can I do?

It probably just needs to know where to find the libraries it needs. You can use patchelf to set the library path and dynamic linker appropriately:

# mybinaryprogram.nix
with import <nixpkgs> {}; with xlibs;
stdenv.mkDerivation rec {
  name = "somename";
  buildInputs = [ makeWrapper ];
  buildPhase = "true";
  libPath = lib.makeLibraryPath [ libXrandr libXinerama libXcursor ];
  unpackPhase = "true";
  installPhase = ''
    mkdir -p $out/bin
    cp ${./mybinaryprogram} $out/bin/mybinaryprogram
    patchelf \
    --set-interpreter "$(< "$NIX_CC/nix-support/dynamic-linker")" \
    --set-rpath "${libPath}" \
    $out/bin/mybinaryprogram
  '';
}

This can be built with:

nix-build mybinaryprogram.nix

And run with:

./result/bin/mybinaryprogram

Another possibility is using a FHS-compatible Sandbox with buildFHSUserEnv

# fhsUser.nix
{ pkgs ? import <nixpkgs> {} }:
(pkgs.buildFHSUserEnv {
  name = "example-env";
  targetPkgs = pkgs: with pkgs; [
    coreutils
  ];
  multiPkgs = pkgs: with pkgs; [
    zlib
    xorg.libXxf86vm
    curl
    openal
    openssl_1_0_2
    xorg.libXext
    xorg.libX11
    xorg.libXrandr
    mesa_glu
  ];
  runScript = "bash";
}).env

the sandbox can be entered with

nix-shell fhsUser.nix

What are channels and how they get updated?

Nixpkgs is the git repository containing all packages and NixOS modules/expressions. Installing packages directly from Nixpkgs master branch is possible but a bit risky as git commits are merged into master before being heavily tested. That's where channels are useful.

A "channel" is a name for the latest "verified" git commits in Nixpkgs. Each channel has a different definition of what "verified" means. Each time a new git commit is verified, the channel declaring this verification gets updated. Contrary to an user of the git master branch, a channel user will benefit both from verified commits and binary packages from the binary cache.

Channels are reified as git branches in the nixpkgs-channels repository and as disk images in the channels webpage. There are several channels, each with its own use case and verification phase:

  • nixos-unstable
  • description Use this when you want the latest package and module versions while still benefiting from the binary cache. You can use this channel on non-NixOS systems. This channel corresponds to NixOS’s main development branch, and may thus see radical changes between channel updates. This channel is not recommended for production systems.
  • definition this channel is updated depending on release.nix and release-lib.nix
  • nixos-unstable-small
  • description This channel is identical to nixos-unstable described above, except that this channel contains fewer binary packages. This means the channel gets updated faster than nixos-unstable (for instance, when a critical security patch is committed to NixOS’s source tree). However, the binary cache may contain less binary packages and thus using this channel may require building more packages from source than nixos-unstable. This channel is mostly intended for server environments and as such contains few GUI applications.
  • definition this channel is updated depending on release-small.nix and release-lib.nix
  • nixos-YY.MM (where YY is a 2-digit year and MM is a 2-digit month, such as nixos-17.03)
  • description These channels are called stable and only get conservative bug fixes and package upgrades. For instance, a channel update may cause the Linux kernel on your system to be upgraded from 3.4.66 to 3.4.67 (a minor bug fix), but not from 3.4.x to 3.11.x (a major change that has the potential to break things). Stable channels are generally maintained until the next stable branch is created.
  • definition this channel is updated depending on release.nix and release-lib.nix
  • nixos-YY.MM-small (where YY is a 2-digit year and MM is a 2-digit month, such as nixos-15.09-small)
  • description The difference between nixos-YY.MM-small and nixos-YY.MM is the name as the one between nixos-unstable-small and nixos-unstable (see above)

Channel update works as follows:

  1. Each channel has a particular job at hydra.nixos.org which must succeed:
  • For NixOS: the trunk-combined tested job, which contains some automated NixOS tests.
  • For nixos-small: the unstable-small tested job.
  • For nixpkgs: the trunk unstable job, which contains some critical release packages.
  1. Once the job succeeds at a particular nixpkgs commit, cache.nixos.org will download binaries from hydra.nixos.org.
  2. Once the above download completes, the channel updates.

You can checkout the nixpkgs git and reset it to a particular commit of a channel. This will not affect your access to the binary cache.

How do I know where's nixpkgs channel located and at which commit?

First echo $NIX_PATH to see where nix looks for the expressions. Note that nix-env uses ~/.nix-defexpr regardless of $NIX_PATH.

If you want to know where <nixpkgs> is located:

nix-instantiate --find-file nixpkgs

To know the commit, open the .version-suffix file in the nixpkgs location. The hash after the dot is the git commit.

An error occurs while fetching sources from an url, how do I fix it?

First try to update the local nixpkgs expressions with nix-channel --update (these describe where to download sources from and how to build them). Try your build again and the url might have already been correctly updated for the package in question. You can also subscribe the unstable channel (which includes the most up-to-date expressions) with nix-channel --add http://nixos.org/channels/nixpkgs-unstable, update and try the build again.

If that fails you can update the url in the nix expression yourself. Navigate to your channel's expressions and find the package in one of the subdirectories. Edit the respective default.nix file by altering the url and sha256. You can use nix-prefetch-url url to get the SHA-256 hash of source distributions.

If the shell complains that you do not have write privileges for the file system, you will have to enable them.

start a new shell with a private mount namespace (Linux-only)

sudo unshare -m bash

remount the filesystem with write privileges (as root)

mount -o remount,rw /nix/store

update the file

nano <PATH_TO_PACKAGE>/default.nix

exit to shell where /nix/store is still mounted read-only

exit

Be sure to report the incorrect url or fix it yourself.

How do I know the sha256 to use with fetchgit/fetchsvn/fetchbzr/fetchcvs?

Install nix-prefetch-scripts and use the corresponding nix prefetch helper.

For instance to get the checksum of a git repository use:

nix-prefetch-git https://git.zx2c4.com/password-store

Should I use http://hydra.nixos.org/ as a binary cache?

Short answer: no.

http://cache.nixos.org is hosted on AWS S3, so it is fast and efficient, but it only contains binaries for nix channels (nixos-unstable, nixpkgs-unstable, and some stable channels too).

So, if the channel is way behind, you may see recommendations to add http://hydra.nixos.org/ as a binary cache, as it contains all recent builds, including ones not pushed to channels.

Unfortunately, due to poor caching, http://hydra.nixos.org/ needs to calculate what is available every time you ask about substitutes, so using it regularly as a cache will slow down the build machines.

Thus, the recommended configuration is to not put http://hydra.nixos.org/ in any config file or automated script. But if you are working on nixpkgs master, then the binary cache provided by Hydra can be very helpful. In such a case, you can add the Hydra cache to the trusted binary caches in nix.conf or configuration.nix, restart the Nix daemon, and use --option extra-binary-caches http://hydra.nixos.org/ in whatever commands are convenient.

I'm trying to install NixOS but my Wifi isn't working and I don't have an ethernet port

Most phones will allow you to share your Wifi connection over USB. On Android you can enable this setting via Settings > Wireless & Networks / More ... > Tethering & portable hotspot > USB tethering. This should be enough to allow you to install NixOS, and then fix your Wifi. iPhones only let you tether using your data connection rather than WiFi.

How can I disable the binary cache and build everything locally?

Set the binary caches to an empty list: nix.binaryCaches = []; in _configuration.nix or pass ad-hoc --option binary-caches "" as parameter to nix-build or its wrappers.

This is also useful to make simple configuration changes in NixOS (ex.: network related), when no network connectivity is available:

nixos-rebuild switch --option binary-caches ""

How do I enable chrooted builds on non-NixOS?

Two options have to be added to make chrooted builds work on Nix, build-use-chroot and build-chroot-dirs:

# /etc/nix/nix.conf
build-use-chroot = true
build-chroot-dirs = $(nix-store -qR $(nix-build '<nixpkgs>' -A bash) | xargs echo /bin/sh=$(nix-build '<nixpkgs>' -A bash)/bin/bash)

On NixOS set the following in configuration.nix:

nix.extraOptions = ''
  build-use-sandbox = true
'';

I cannot find $package when running nix-env -qaP even with channels configured

Not all packages are listed. Packages may not be listed because: - the package is unfree, like e.g. unrar and teamspeak_client; - the package is part of an attribute set and nix-env doesn't recurse into this set (see pkgs.recurseIntoAttrs)

How can I install a proprietary or unfree package?

If you want to install an unfree package as a user, then you need to enable it in ~/.nixpkgs/config.nix:

{
  ...
  allowUnfree = true;
}

If you want to enable unfree packages system-wide, then set in your /etc/nixos/configuration.nix:

{
  ...
  nixpkgs.config.allowUnfree = true;
}

For temporary allowing unfree packages you can set the environment variable NIXPKGS_ALLOW_UNFREE, e.g.

NIXPKGS_ALLOW_UNFREE=1 nix-env

How can I install a package from unstable while remaining on the stable channel?

It is possible to have multiple nix-channels simultaneously. To add the unstable channel with the specifier unstable,

sudo nix-channel --add https://nixos.org/channels/nixos-unstable unstable

After updating the channel

sudo nix-channel --update unstable

queries via nix-env (or nox) will show packages from both stable and unstable. Use this to install unstable packages into your user environment. The following snippet shows how this can be done in configuration.nix.

{ config, pkgs, ... }:
let
  unstable = import <nixos-unstable> {};
in {
  environment.systemPackages = [ unstable.PACKAGE_NAME ];
}

What is the origin of the name Nix

The name Nix is derived from the Dutch word niks, meaning nothing;build actions do not see anything that has not been explicitly declared as an input > Nix: A Safe and Policy-Free System for Software Deployment, page 2