簡體   English   中英

運行中的 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 權限。 有沒有辦法通過修改 Dockerfle 或更改我的代碼來解決這個問題?

另一個問題並不能完全幫助。 我正在使用的文件夾是在我的 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文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM