我可以使用 Nix 指定 Docker 镜像:
{ 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" ];
};
}
这可行,但生成的映像以 root 身份运行。如何扩展此示例以添加非 root 用户(最好具有特定的 UID/GID)并指定容器与该用户一起运行?
答案1
它与普通 docker 安装中的操作非常接近,只是您需要确保加载shadowSetup
以创建/etc/passwd
文件等如手册中所述:
{ 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";
};
}
如果需要,您可以使用 的标准参数配置 uid/gid useradd
。
演示:
$ docker load < $(nix-build test.nix)
…
Loaded image: delme:latest
$ docker run -ti delme:latest
bash-5.1$ whoami
redis
PS:nix社区比较活跃https://discourse.nixos.org所以您下次可能想在那里提出您的问题以获得更快的答案;-)