Docker - parent image execution fails due to missi

2019-08-17 07:20发布

问题:

The parent image I am using seems to require root access to run its ENTRYPOINT instruction.

In my Dockerfile I need to run my own container (executable) with normal user at the end. How do I switch back and forth between users here?

Psuedo Dockerfile:

FROM parentrepo/parentimg # its Dockerfile probably has ENTRYPOINT at the end which requires root access
#my app specific instructions
WORKDIR ..
RUN mkdir ..
COPY ..
RUN tar ..
EXPOSE 9000
USER nir # HEre i want to switch user to nir
WORKDIR ${myhome}
CMD ["/bin/bash", "-c", "./start"]

Running above fails as parent requires sudo access. if I don't do USER nir then my process starts as root user which i don't want. Does the parent Dockerfile need to have USER root here ?

Also, Is there any document that describe how docker Build execute instructions at high level? . How it interacts with hierarchies of parent Dockerfiles. Looks like it imports instructions from parent docker files; creates one docker file. Does it reorder instruction in anyway?

ANd what happens at runtime which executing via docker run ? I know RUN command is used at build time while CMD and ENTRYPOINT executed at runtime but it still doesn't explain whole picture and sequences from build otherwise it would have been clear what I need to do.

回答1:

You should create a user nir inside that image and also give appropriate ownership and rights to execute that ./start script.

Here is what I tried and it worked.

  • Created a Dockerfile with following contents
FROM alpine
WORKDIR /
#RUN useradd -ms /bin/bash nir <= (This will work for non-alpine images)
RUN addgroup -S appgroup && adduser -S nir -G appgroup
COPY . /
RUN chown nir:appgroup /start.sh
RUN chmod +x /start.sh
USER nir
CMD ["/bin/sh", "-c", "/start.sh"]
  • Contents of start.sh script.
#!/bin/sh
echo "hello" > /tmp/abc.txt
sleep 100
exec "$@"
  • Build and run the container.
$ docker run -itd  t:t .
$ docker run -itd  t:t
$ docker exec -it de11dbffb2ca sh
/ $ ls /tmp/abc.txt
/tmp/abc.txt
/ $ cat /tmp/abc.txt
hello
/ $ ls -ltrh /tmp/
total 4K
-rw-r--r--    1 nir      appgroup       6 Jun 21 04:35 abc.txt
/ $

As you can see the script start.sh is successfully executed by user nir. Here we just created appropriate user using adduser for alpine based image (or use useradd for non-alpine images). Given appropriate permission to the script using chown and chmod.

Hope this helps, let me know.