Use sudo inside Dockerfile (Alpine)

ridermansb picture ridermansb · Mar 11, 2018 · Viewed 40.1k times · Source

I have this Dockerfile ...

FROM keymetrics/pm2:latest-alpine

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

COPY . ./

EXPOSE 1886 80 443

CMD pm2-docker start --auto-exit --env ${NODE_ENV} ecosystem.config.js

How can I execute the CMD command using sudo ?

I need to do this because the port 443 is allowed only for sudo user.

Answer

Gerbrand picture Gerbrand · Mar 21, 2019

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>