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