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