2

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.

AlejoDiaz49
  • 95
  • 2
  • 8
  • Does this answer your question? [How to give folder permissions inside a docker container Folder](https://stackoverflow.com/questions/45972608/how-to-give-folder-permissions-inside-a-docker-container-folder) – user93353 Nov 23 '20 at 14:11
  • If you post your Dockerfile, we can easily help you. By the way, you can try to insert `USER root` in your Dockerfile. – Stefano Fiorucci - anakin87 Nov 23 '20 at 14:17
  • That other issue 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 the access in advance. I can't really share the Dockerfile, but it is pretty much an Ubuntu image. I would really like to avoid leaving root as the default user for [security reasons](https://snyk.io/blog/10-docker-image-security-best-practices/), although I could consider it if there is no other choice – AlejoDiaz49 Nov 23 '20 at 14:17
  • 1
    Please provide a [mcve] with an example Dockerfile and C++ code that we can copy/paste and run ourselves to reproduce your issue. This doesn't/shouldn't be a full copy of your actual code, just a minimal working example. – BMitch Dec 01 '20 at 10:05

1 Answers1

2

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.

pptaszni
  • 5,591
  • 5
  • 27
  • 43