1<section xmlns="http://docbook.org/ns/docbook"
2 xmlns:xlink="http://www.w3.org/1999/xlink"
3 xmlns:xi="http://www.w3.org/2001/XInclude"
4 version="5.0"
5 xml:id="sec-declarative-containers">
6
7<title>Declarative Container Specification</title>
8
9<para>You can also specify containers and their configuration in the
10host’s <filename>configuration.nix</filename>. For example, the
11following specifies that there shall be a container named
12<literal>database</literal> running PostgreSQL:
13
14<programlisting>
15containers.database =
16 { config =
17 { config, pkgs, ... }:
18 { services.postgresql.enable = true;
19 services.postgresql.package = pkgs.postgresql92;
20 };
21 };
22</programlisting>
23
24If you run <literal>nixos-rebuild switch</literal>, the container will
25be built. If the container was already running, it will be
26updated in place, without rebooting. The container can be configured to
27start automatically by setting <literal>containers.database.autoStart = true</literal>
28in its configuration.</para>
29
30<para>By default, declarative containers share the network namespace
31of the host, meaning that they can listen on (privileged)
32ports. However, they cannot change the network configuration. You can
33give a container its own network as follows:
34
35<programlisting>
36containers.database =
37 { privateNetwork = true;
38 hostAddress = "192.168.100.10";
39 localAddress = "192.168.100.11";
40 };
41</programlisting>
42
43This gives the container a private virtual Ethernet interface with IP
44address <literal>192.168.100.11</literal>, which is hooked up to a
45virtual Ethernet interface on the host with IP address
46<literal>192.168.100.10</literal>. (See the next section for details
47on container networking.)</para>
48
49<para>To disable the container, just remove it from
50<filename>configuration.nix</filename> and run <literal>nixos-rebuild
51switch</literal>. Note that this will not delete the root directory of
52the container in <literal>/var/lib/containers</literal>. Containers can be
53destroyed using the imperative method: <literal>nixos-container destroy
54 foo</literal>.</para>
55
56<para>Declarative containers can be started and stopped using the
57corresponding systemd service, e.g. <literal>systemctl start
58container@database</literal>.</para>
59
60</section>