容器内使用 apt-get 操作失败,除非使用 sudo

3

我注意到一个问题,即在容器内使用apt-get install时会失败,原因如下:

  1. 该软件包已经安装过了,
  2. 没有使用sudo。

可以通过创建一个简单的容器来重新创建这个问题,例如:

docker run -it ubuntu:latest /bin/bash 

在容器中运行以下命令:

apt-get install software-properties-common
apt-get install software-properties-common

第二次尝试会失败并显示“已终止”信息。如果在语句前加上sudo,它将成功执行:
sudo apt-get install software-properties-common 

如果容器内的用户是root,为什么重新安装现有软件包时需要sudo呢?我不认为这与AUFS文件系统有关,因为使用sudo前缀将能够完成操作。
这是使用Docker 1.10和Ubuntu镜像。

1
你应该先执行 apt-get update - user2915097
如果我像你一样操作,第一个apt-get安装成功了,但第二个命令却提示“software-properties-common已经是最新版本。0个升级,0个新安装,0个要删除,0个未升级。”,所以肯定有问题。我的系统是Ubuntu 14.04,使用的docker版本是1.10.2-rc1。 - user2915097
这没有任何区别。关键是要使用sudo。如果使用apt-get install software-properties-common && apt-get update,然后再使用apt-get install software-properties-common将会失败。如果您使用sudo apt-get install software-properties-common,则可以成功安装。这个问题的核心在于需要使用sudo,即使您已经是root用户。 - wildpalms
@user2915097没有起作用。apt-get update 正在读取软件包列表... 完成 E: 无法打开锁定文件/var/lib/apt/lists/lock - 打开(13:权限被拒绝) E: 无法锁定目录/var/lib/apt/lists/` - Charlie Parker
1
当容器中既没有sudo也没有apt-get时,您可以使用命令docker exec -u root -t -i container_id /bin/bash以root用户身份跳转到正在运行的容器中。您尝试过这个吗? - Charlie Parker
显示剩余2条评论
2个回答

0
主要重点是使用 sudo。
在 Debian 11 上不会失败。
# docker run -it ubuntu:latest /bin/bash
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
00f50047d606: Pull complete
Digest: sha256:20fa2d7bb4de7723f542be5923b06c4d704370f0390e4ae9e1c833c8785644c1
Status: Downloaded newer image for ubuntu:latest
#  apt-get update
Hit:1 http://ports.ubuntu.com/ubuntu-ports jammy InRelease
Hit:2 http://ports.ubuntu.com/ubuntu-ports jammy-updates InRelease
Hit:3 http://ports.ubuntu.com/ubuntu-ports jammy-backports InRelease
Hit:4 http://ports.ubuntu.com/ubuntu-ports jammy-security InRelease
Reading package lists... Done
# apt-get install software-properties-common
Reading package lists... Done
...
0 added, 0 removed; done.
Running hooks in /etc/ca-certificates/update.d...
done.
Processing triggers for dbus (1.12.20-2ubuntu4) ...
# apt-get install software-properties-common
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
software-properties-common is already the newest version (0.99.22.3).
0 upgraded, 0 newly installed, 0 to remove and 4 not upgraded.

你的系统可能存在某些损坏。如果运行这些操作没有帮助,你可能需要重新安装:

apt-get update
apt-get upgrade

-2

您需要按照以下命令安装sudo软件包。

apt update && apt upgrade apt install sudo


问题不在于如何安装sudo,而在于为什么OP在以root身份运行时没有使用sudo时apt会失败。 - Charles Duffy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接