如何在Docker/Podman容器内永久设置根目录为共享挂载
解决无根Podman容器内的根目录共享挂载警告
为什么Dockerfile里RUN mount --make-rshared /会失败
mount是内核级操作,需要CAP_SYS_ADMIN权限,而镜像构建阶段的root用户是受限的,没有完整内核权限,所以执行这个命令会直接报Permission denied——这和yum、useradd这类用户空间命令不一样,后者不需要内核级权限。
正确的镜像配置方案
1. 写个entrypoint脚本处理启动时的mount
构建阶段做不了的事,放到容器启动时来做。思路是:容器启动先以root身份执行mount,再切换到普通用户跑Podman。
创建entrypoint.sh脚本:
#!/bin/bash # 先配置根目录为共享挂载 mount --make-rshared / # 切换到预先创建的普通用户(比如podman-user) exec su - podman-user -c "$*"
给脚本加执行权限:chmod +x entrypoint.sh
2. 更新Dockerfile
# 用你需要的基础镜像,比如红帽的ubi8 FROM registry.access.redhat.com/ubi8/ubi # 创建普通用户并配置Podman权限 RUN useradd -m podman-user && \ echo "podman-user ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/podman-user && \ chmod 0440 /etc/sudoers.d/podman-user # 复制entrypoint脚本到容器内 COPY entrypoint.sh /usr/local/bin/ # 设置容器启动入口 ENTRYPOINT ["entrypoint.sh"] # 默认启动命令,比如进入bash CMD ["bash"]
3. 启动容器的正确姿势
启动时要给容器足够权限执行mount,最简单的是加--privileged参数:
podman run -it --privileged 你的镜像名
这样启动后,entrypoint会自动完成mount配置,切换到普通用户后再跑podman info,警告就消失了。
为什么/etc/init.d脚本没生效
容器默认不会启动systemd或传统init系统,所以/etc/init.d下的脚本不会自动执行。除非你特意配置容器启动systemd,这反而麻烦,不如用entrypoint直接处理更高效。
顺带解决小问题
- 缺
login和runlevel命令:在Dockerfile里加RUN yum install -y util-linux initscripts就能装上。
内容的提问来源于stack exchange,提问作者siggi
相关产品推荐
相关产品推荐

