1

I can use Nix to specify a Docker image:

{ pkgs ? import <nixpkgs> { }
, pkgsLinux ? import <nixpkgs> { system = "x86_64-linux"; }
}:
pkgs.dockerTools.buildImage {
  name = "delme";
  tag = "latest";
  contents = pkgs.buildEnv {
    name = "image-root";
    paths = with pkgsLinux; [
      bashInteractive
      coreutils
      curl
    ];
    pathsToLink = [ "/bin" ];
  };
  config = {
    Cmd = [ "${pkgsLinux.bashInteractive}/bin/bash" ];
  };
}

This works, but the resultant image runs as root. How can I extend this example to add a non-root user (ideally with a specific UID/GID) and specify that the container runs with that user?

1 Answer 1

1

It's quite close to what you would do on a normal docker install, except that you need to make sure to load shadowSetup to create the /etc/passwd files and more as documented in the manual:

{ pkgs ? import <nixpkgs> { }
, pkgsLinux ? import <nixpkgs> { system = "x86_64-linux"; }
}:
pkgs.dockerTools.buildImage {
  name = "delme";
  tag = "latest";
  contents = pkgs.buildEnv {
    name = "image-root";
    paths = with pkgsLinux; [
      bashInteractive
      coreutils
      curl
    ];
    pathsToLink = [ "/bin" ];
  };
  # Add a new user
  # shadowSetup creates the necessary files to deal with new others
  # like /etc/passwd as documented in
  # https://nixos.org/manual/nixpkgs/stable/#ssec-pkgs-dockerTools-shadowSetup
  runAsRoot = ''
    #!${pkgsLinux.runtimeShell}
    ${pkgsLinux.dockerTools.shadowSetup}
    groupadd -r redis
    useradd -r -g redis redis
  '';
  config = {
    Cmd = [ "${pkgsLinux.bashInteractive}/bin/bash" ];
    User = "redis:redis";
  };
}

If needed you can configure the uid/gid using the standard arguments of useradd.

Demo:

$ docker load < $(nix-build test.nix)
…
Loaded image: delme:latest
$ docker run -ti delme:latest
bash-5.1$ whoami 
redis

PS: the nix community is more active on https://discourse.nixos.org so you might want to ask your question there next time to get a faster answer ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .