运行 Docker 容器内不允许操作 chmod 0777
Operation chmod 0777 not permitted inside a running Docker container
我正在尝试在调用命令的 Docker 容器中对我的 C++ 代码执行一些单元测试:
...
if (chmod("/tmp/ipc_unixdomain", 0777) != 0) {
...
在容器外的我的 PC 中,我可以在终端和 C++ 代码中 运行 此命令,但是一旦我移入容器内部,我只能在 运行 作为 root 用户或使用 sudo。如果我不这样做,我会收到错误消息
Operation not permitted
我想要一种无需 sudo 权限即可正常执行测试的方法。 有没有办法通过修改 Docker 文件或更改我的代码来解决这个问题?
问题并没有完全帮助。我正在使用的文件夹是在我的 C++ 程序执行期间创建的,所以我想我不能提前授予访问权限。
很可能您以错误的方式创建了 docker 用户,或者使用了错误的工作区。试试这个基于 Ubuntu-18.04 Dockerfile
的例子:
FROM ubuntu:18.04
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y g++
RUN useradd -ms /bin/bash newuser
USER newuser
WORKDIR /home/newuser
COPY script.sh script.sh
COPY main.cpp main.cpp
RUN ./script.sh
script.sh
#!/bin/bash
touch /tmp/xxx
chmod 0777 /tmp/xxx
echo "$(ls -lah /tmp)" > output
g++ main.cpp -o main
./main >> output
main.cpp
/*
* Docker chmod example
*/
#include <sys/stat.h>
#include <fstream>
#include <iostream>
constexpr auto filename = "/tmp/yyy";
int main()
{
{
std::ofstream of(filename);
}
std::cout << "c++ chmod result = " << chmod(filename, 0777) << std::endl;
return 0;
}
创建容器,运行它并检查结果。它应该能够使用 bash 和 C++ 可执行文件使用 chmod 0777 创建 /tmp/xxx
和 /tmp/yyy
文件。
我正在尝试在调用命令的 Docker 容器中对我的 C++ 代码执行一些单元测试:
...
if (chmod("/tmp/ipc_unixdomain", 0777) != 0) {
...
在容器外的我的 PC 中,我可以在终端和 C++ 代码中 运行 此命令,但是一旦我移入容器内部,我只能在 运行 作为 root 用户或使用 sudo。如果我不这样做,我会收到错误消息
Operation not permitted
我想要一种无需 sudo 权限即可正常执行测试的方法。 有没有办法通过修改 Docker 文件或更改我的代码来解决这个问题?
很可能您以错误的方式创建了 docker 用户,或者使用了错误的工作区。试试这个基于 Ubuntu-18.04 Dockerfile
的例子:
FROM ubuntu:18.04
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y g++
RUN useradd -ms /bin/bash newuser
USER newuser
WORKDIR /home/newuser
COPY script.sh script.sh
COPY main.cpp main.cpp
RUN ./script.sh
script.sh
#!/bin/bash
touch /tmp/xxx
chmod 0777 /tmp/xxx
echo "$(ls -lah /tmp)" > output
g++ main.cpp -o main
./main >> output
main.cpp
/*
* Docker chmod example
*/
#include <sys/stat.h>
#include <fstream>
#include <iostream>
constexpr auto filename = "/tmp/yyy";
int main()
{
{
std::ofstream of(filename);
}
std::cout << "c++ chmod result = " << chmod(filename, 0777) << std::endl;
return 0;
}
创建容器,运行它并检查结果。它应该能够使用 bash 和 C++ 可执行文件使用 chmod 0777 创建 /tmp/xxx
和 /tmp/yyy
文件。