How can I run ENTRYPOINT as root user?
Asked Answered
K

1

19

This is a part of my dockerfile:

COPY ./startup.sh /root/startup.sh
RUN chmod +x /root/startup.sh

ENTRYPOINT ["/root/startup.sh"]

EXPOSE 3306
CMD ["/usr/bin/mysqld_safe"]

USER jenkins

I have to switch in the end to USER jenkins and i have to run the container as jenkins.

My Question is now how can I run the startup.sh as root user when the container starts?

Kaela answered 21/11, 2017 at 10:1 Comment(2)
try this CMD ["/usr/bin/mysqld_safe", "&& su - jenkins"]Saida
When I do this i am getting an other error: mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended --------> I think that the command mysqld_safe is done by user jenkins. Any further tips?Kaela
S
19

Delete the USER jenkins line in your Dockefile.

Change the user at the end of your entrypoint script (/root/startup.sh).

by adding: su - jenkins man su

Example:

Dockerfile

FROM debian:8

RUN useradd -ms /bin/bash exemple

COPY entrypoint.sh /root/entrypoint.sh

ENTRYPOINT "/root/entrypoint.sh"

entrypoint.sh

#!/bin/bash

echo "I am root" && id

su - exemple

# needed to run parameters CMD
$@

Now you can run

$ docker build -t so-test .
$ docker run --rm -it so-test bash
I am root
uid=0(root) gid=0(root) groups=0(root)
exemple@37b01e316a95:~$ id
uid=1000(exemple) gid=1000(exemple) groups=1000(exemple)

It's just a simple example, you can also use the su -c option to run command with changing user.

Selfmortification answered 21/11, 2017 at 10:10 Comment(8)
This should mean when I e.g. run: docker exec -it <CONTAINER-ID> /bin/bash ------ i should be the jenkins user?Kaela
My preference is an exec gosu rather than an su command, to handle signals.Peregrination
@Peregrination Can you give an example?Kaela
This gets the job done, the only thing is that when running docker exec -it <CONTAINER-ID> /bin/bash, we will be the root user, which is kind of annoying, I guess. Any solutions?Magnesite
@Magnesite This doesn't really answers your question, but when using docker-compose it is possible to add user: jenkins in the docker-compose.yml file, then running in terminal: docker-compose exec {service-name} /bin/bashHesiod
In the beginning, I thought this was the perfect solution. The idea of having a non-root user is for security reasons. We this approach you are keeping the root user always.Dotdotage
@Magnesite $docker exec -u <USERNAME> -it <CONTAINER-ID> /bin/bashSidestroke
How does this work? Why doesn't su do what it normally does and try to open an interactive shell, with the script continuing as root once the shell terminates?Libove

© 2022 - 2024 — McMap. All rights reserved.