Szczepan Hołyszewski
Szczepan Hołyszewski

Reputation: 3175

Run a command as root with docker-compose?

While in the process of painstakingly sculpting a Dockerfile and docker-compose.yml, what is THE RIGHT WAY to run root shell in work-in-progress containers (without actually starting their services!) in order to debug issues? I need to be able to run the shell as root, because only root has full access to files containing the information that I need to examine.

I can modify Dockerfile and docker-compose.yml in order to achieve this goal; as I wrote above, I am in the process of sculpting those anyway.

The problem however is that about the only way I can think of is putting USER root in Dockerfile or user: root in docker-compose.yml, but those SimplyHaveNoEffect™ in the docker-compose run <service> bash scenario. whoami in the shell thus started says neo4j instead of root, no matter what I try.

I might add sudo to the image, which doesn't have sudo, but this should be considered last resort. Also using docker directly instead of docker-compose is less than preferable.

Upvotes: 13

Views: 24977

Answers (2)

Amado Saladino
Amado Saladino

Reputation: 2692

You can also use it this way:

version: '3'
services:
  jenkins:
    user: root
    image: jenkins/jenkins:lts
    ports: 
      - "8080:8080"
      - "50000:50000"
    volumes:
      - /jenkins:/var/jenkins_home

you can refer to How to configure docker-compose.yml to up a container as root

Upvotes: 5

David Maze
David Maze

Reputation: 159485

All of the commands that launch shells in containers (including, for example, docker-compose run have a --user option and so you can specify an arbitrary user for your debugging shell.

docker-compose run -u root <service> bash

If you're in the process of debugging your image build, note that each build step produces an image, and you can run a debugging shell on that image. (For example, examine the step before a RUN step to see what the filesystem looks like before it executes, or after to see its results.)

$ docker build .
...
Step 7/9 : RUN ...
 ---> Using cache
 ---> 55c91a5dca05
...
$ docker run --rm -it -u root 55c91a5dca05 bash

In both of these cases the command (bash) overrides the CMD in the Dockerfile. If you have an ENTRYPOINT wrapper script that will still run, but the standard exec "$@" command will launch your debugging shell. If you've put your default command to run as ENTRYPOINT, change it to CMD to better support this use case (and also the wrapper entrypoint pattern, should you need it).

If you really can't change the Dockerfile, you can override the ENTRYPOINT too, but it's a little awkward.

docker run --rm -it -u root --entrypoint ls myimage -al /app

Upvotes: 18

Related Questions