Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ENTRYPOINT: first run command as root, then start shell for non-root user

I'm writing a Dockerfile for an image that, when run, performs the following two things in order:

  1. Start up a daemon as root
  2. Start up an interactive shell as a non-root user

The problem is that ENTRYPOINT can only be run as a single user (whichever USER is set last before ENTRYPOINT in the Dockerfile). In this case, the ENTRYPOINT can only run as either root or the non-root user.

I can't put CMD commands before ENTRYPOINT, because they just get overridden by ENTRYPOINT.

How can I accomplish what I need?

like image 994
pcdangio Avatar asked Apr 29 '26 21:04

pcdangio


1 Answers

You start your container as root. This runs your entrypoint as root. Perform all the steps you need, then make the last step look like:

exec gosu username /bin/bash

To launch /bin/bash as the user username. You can find gosu in this github repo. It has the advantage of running an su command with an implicit exec which avoids leaving the parent process around which can break signal handling.

If you make /bin/bash the value of CMD, you can make this more flexible with:

exec gosu username "$@"

Make sure to use the JSON syntax for ENTRYPOINT and CMD to avoid issues with the merged commands and cli args.

This is preferable over sudo since it avoids any option to go back from the user to root.

like image 179
BMitch Avatar answered May 01 '26 11:05

BMitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!