Search code examples
c++linuxdockersudochmod

Operation chmod 0777 not permitted inside a running Docker container


I am trying to execute some unit testing for my C++ code inside a Docker container that calls the command:

...
if (chmod("/tmp/ipc_unixdomain", 0777) != 0) {
...

In my PC outside of the container, I am able to run this command in both the terminal and the C++ code, but once I move inside the container I am only able to execute them if I run as the root user or with sudo. If I don't do it like that I get the error message

Operation not permitted

I would like to have a way to normally execute my tests without the need for sudo privileges. Is there a way to solve this by modifying the Dockerfle or changing my code?

This other question does not completely help. The folder I am using is created during the execution of my C++ program, so I think I can't give access in advance.


Solution

  • Most likely you created the docker user in a wrong way, or used the wrong workspace. Try this Ubuntu-18.04 based Dockerfile as an example:

    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;
    }
    

    Create the container, run it and check the results. It should be able to create both /tmp/xxx and /tmp/yyy files with chmod 0777 using bash and C++ executable.