Use sudo inside Dockerfile (Alpine)

后端 未结 2 863
长情又很酷
长情又很酷 2021-01-08 00:40

I have this Dockerfile ...

FROM keymetrics/pm2:latest-alpine

RUN apk update && \\
    apk upgrade && \\
    apk add \\
       bash

COPY . .         


        
相关标签:
2条回答
  • 2021-01-08 01:08

    Sudo isn't shipped with Alpine images normally, and it rarely makes sense to include it inside of any container. What you need isn't sudo to bind to a low numbered port, but the root user itself, and sudo is just a common way to get root access in multi-user environments. If a container included sudo, you would need to either setup the user with a password, or allow commands to run without a password. Regardless of which you chose, you now have a privilege escalation inside the container, defeating the purpose of running the container as a normal user, so you may as well run the container as root at that point.

    If the upstream image is configured to run as a non-root user (unlikely since you run apk commands during the build), you can specify USER root in your Dockerfile, and all following steps will run as root by default, including the container entrypoint/cmd.

    If you start your container as a different user, e.g. docker run -u 1000 your_image, then to run your command as root, you'd remove the -u 1000 option. This may be an issue if you run your container in higher security environments that restrict containers to run as non-root users.

    If your application itself is dropping the root privileges, then including sudo is unlikely not help, unless the application itself has calls to sudo internally. If that's the case, update the application to drop root privileges after binding to the ports.

    Most importantly, if the only reason for root inside your container is to bind to low numbered ports, then configure your application inside the container to bind to a high numbered port, e.g. 8080 and 8443. You can map this container port to any port on the host, including 80 and 443, so the outside world does not see any impact. E.g. docker run -p 80:8080 -p 443:8443 your_image. This simplifies your image (removing tools like sudo) and increases your security at the same time.

    0 讨论(0)
  • 2021-01-08 01:25

    The su-exec can be used in alpine. Do add it the package, if not already available, add the following to your Dockerfile

    RUN apk add --no-cache su-exec
    

    Inside your scripts you'd run inside docker you can use the following to become another user:

    exec su-exec <my-user> <my command>
    

    Alternatively, you could add the more familiair sudo package while building your docker-file Add the following to your Dockerfile that's FROM alpine

    RUN set -ex && apk --no-cache add sudo
    

    After that you can use sudo

    sudo -u <my-user> <my command>
    
    0 讨论(0)
提交回复
热议问题