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