Nix & NixOS: Declarative Docker on NixOS

While you might be tempted to run all your applications natively in nix, there might come the time when you find something that is not packaged in nix and only available as a docker image.

While you obviously can run docker containers like you would do on any other Linux distribution after installing the docker package, you might want to specify the containers decoratively inside your configuration.nix.

Guess what? NixOS will happily do it for you! I’ve been using the bitwarden password manager for a while, specifically I’m hosting the bitwarden_rs bitwarden compatible server written in Rust.

Consider the following command used to run an instance of the container on my old server:

sudo docker run -d --restart unless-stopped \
	-e DOMAIN=https://pw.mydomain.com \
	-e YUBICO_CLIENT_ID=12345 \
	-e YUBICO_SECRET_KEY=myYubicoSecretKeyString \
	-e ADMIN_TOKEN=myAdminTokenString \
	-e SIGNUPS_ALLOWED=true \
	-e INVITATIONS_ALLOWED=true \
	--name bitwardenrs \
	-v /var/docker/bitwarden/:/data/ \
	-p 9999:80 bitwardenrs/server:latest

The usual “docker stuff” really, nothing special: An image, some environment variables, some ports and a volume. The command above can be easily “translated” into the following snippet inside your /etc/nixos/configuration.nix file.

virtualisation.oci-containers.containers = {
  bitwardenrs = {
    autoStart = true;
    image = "bitwardenrs/server:latest";
    environment = {
      ADMIN_TOKEN = "myAdminTokenString";
      DOMAIN = "https://pw.mydomain.com";
      INVITATIONS_ALLOWED="true";
      SIGNUPS_ALLOWED = "true";
      YUBICO_CLIENT_ID="12345" ;
      YUBICO_SECRET_KEY="myYubicoSecretKeyString" ;
    };
    ports = [
      "80:80"
    ];
    volumes = [
      "/var/docker/bitwarden/:/data/"
    ];
  };
};

Not much to say here, the syntax should be self-explanatory. After running nixos-rebuild switch confirm that your container is running:

[[email protected]:~] docker ps
CONTAINER ID        IMAGE                       COMMAND             CREATED             STATUS                             PORTS                          NAMES
1843eb5731b5        bitwardenrs/server:latest   "/start.sh"         15 seconds ago      Up 14 seconds (health: starting)   0.0.0.0:80->80/tcp, 3012/tcp   bitwardenrs