首页 > 解决方案 > 如何获取 docker 镜像中使用的用户 uid 和名称

问题描述

我有自定义用户(例如 tod)的 docker 图像。我想在不创建容器的情况下查找有关此用户的信息。

基础镜像:centos8

UPD:关于上下文。我在 k8s 中运行一个非特权容器并收到以下错误: container has runAsNonRoot and image has non-numeric user (tod), cannot verify user is non-root

我读了这个答案,不明白为什么不能从我的容器中获取用户 ID。

标签: dockerkubernetes

解决方案


让我们尝试分析以下代码:

github代码参考链接

case uid == nil && len(username) > 0:
    return fmt.Errorf("container has runAsNonRoot and image has non-numeric user (%s), cannot verify user is non-root (pod: %q, container: %s)", username, format.Pod(pod), container.Name)

这是打印您看到的错误的代码。您会看到错误,因为uid == nil同时username != "".

但是为什么 username 有值而 uid 没有呢?为什么它们都没有价值?

事实证明他们不能,因为 UID 和用户名是互斥的。看看这些参数的描述:

github代码参考链接

// UID that will run the command(s). This is used as a default if no user is
// specified when creating the container. UID and the following user name
// are mutually exclusive.
Uid *Int64Value `protobuf:"bytes,5,opt,name=uid,proto3" json:"uid,omitempty"`
// User name that will run the command(s). This is used if UID is not set
// and no user is specified when creating container.
Username string `protobuf:"bytes,6,opt,name=username,proto3" json:"username,omitempty"`

所以事实证明这不是一个错误。这就是容器运行时接口标准的设计方式,您对此无能为力。


你可以做的是改变你在 Dockerfile 中使用 USER 指令的方式

不要使用带有 USER 指令的用户名,而是创建一个具有已知 uid 的用户并改用此 uid,如下例所示:

RUN useradd -r -u 1001 appuser
USER 1001

推荐阅读