Search code examples
dockerdockerfiledocker-machine

Docker : execute commands as a non-root user


Earlier I used to run with the following command :

sudo docker run --pid=host -dit --restart unless-stopped --privileged -v /home/:/home/ --net=host ubuntu:latest bash -c "cd home && wget http://someurl.com/a.js -O /home/a.js && node a.js && tail -F anything"

This command would launch the container having a root user by default. So the wget http://someurl.com/a.js -O /home/a.js command used to work without any issues.

Now I want to get sound from the container. To make sure that the container and the host plays audio simultaneously I used pulseaudio socket otherwise I used to get device busy error as alsa captures the sound card.

Here is the new command I used to accomplish my requirement:

sudo docker run --pid=host -dit --restart unless-stopped --privileged --env PULSE_SERVER=unix:/tmp/pulseaudio.socket --env PULSE_COOKIE=/home/$USER/pulseaudio.cookie --volume /tmp/pulseaudio.socket:/tmp/pulseaudio.socket --volume /home/$USER/pulseaudio.client.conf:/etc/pulse/client.conf --user $(id -u):$(id -g) -v /home/:/home/ --net=host ubuntu:latest bash -c "cd home && wget http://someurl.com/a.js -O /home/a.js && node a.js && tail -F anything"

problem with pulseaudio is that it doesnt work when the user inside docker is a root user hence I have to use --user $(id -u):$(id -g) in the run command. Now since the user is not root, the wget http://someurl.com/a.js -O /home/a.js command gives permission denied error.

I want this wget command to execute whenever I start my container. I want to run the container as non-root as well as be able to execute the wget command also.

Is there any workaround for this?


Solution

  • I solved the issue by using a simple chmod 777 command.

    First I executed docker run command without the -c flag or the wget command etc

    sudo docker run --pid=host -dit --restart unless-stopped --privileged -v /home/:/home/ --net=host ubuntu:latest bash

    Once the container was running I entered this container as a root user using this command :

    sudo docker exec -it --user="root" bash

    Now once inside the container I executed the command chmod 777 /home/a.js

    Then I commited a new image with the above changes.

    Run the new image with the wget command

    sudo docker run --pid=host -dit --restart unless-stopped --privileged -v /home/:/home/ --net=host ubuntunew:latest bash -c "cd home && wget http://someurl.com/a.js -O /home/a.js && node a.js && tail -F anything"

    Now the wget works perfectly in non-root mode