17

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?

adbo
  • 767
  • 1
  • 8
  • 23
  • 1
    try this `CMD ["/usr/bin/mysqld_safe", "&& su - jenkins"]` – yamenk Nov 21 '17 at 11:55
  • 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? – adbo Nov 21 '17 at 12:53

1 Answers1

20

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.

Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
albttx
  • 3,444
  • 4
  • 23
  • 42
  • This should mean when I e.g. run: docker exec -it /bin/bash ------ i should be the jenkins user? – adbo Nov 21 '17 at 10:39
  • 1
    My preference is an `exec gosu` rather than an `su` command, to handle signals. – BMitch Nov 21 '17 at 13:12
  • @BMitch Can you give an example? – adbo Nov 21 '17 at 13:45
  • 18
    This gets the job done, the only thing is that when running docker exec -it /bin/bash, we will be the root user, which is kind of annoying, I guess. Any solutions? – qichao_he Aug 21 '18 at 19:54
  • 4
    @qichao_he 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/bash` – Gus Apr 09 '19 at 15:24
  • 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. – Frank Escobar Mar 13 '21 at 13:27
  • @qichao_he $docker exec -u -it /bin/bash – Demis Palma ツ Nov 16 '21 at 11:23
  • 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? – dspeyer Dec 02 '21 at 16:31