Skip to content

Instantly share code, notes, and snippets.

@danielTobon43
Last active January 19, 2024 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielTobon43/4c430a3375a4820175a8df77ad554de2 to your computer and use it in GitHub Desktop.
Save danielTobon43/4c430a3375a4820175a8df77ad554de2 to your computer and use it in GitHub Desktop.
Add user and group to Alpine linux Dockerfile

Add user and group Linux Alpine Dockerfile

RUN apk add --no-cache sudo


# creates a pcluser with no password
# then set password to 1234
# this is necessary since adduser from Alpine Linux
# will prompt a password without the --disabled-password flag
ARG USERNAME=alpinedev
RUN adduser --gecos "pcluser" \
    --disabled-password \
    --shell /bin/zsh \
    --uid 1000 \
    ${USERNAME} && \
    echo "$USERNAME:1234" | chpasswd && \
    echo "$USERNAME ALL=(ALL) ALL" > /etc/sudoers.d/$USERNAME && chmod 0440 /etc/sudoers.d/$USERNAME

# creates a group: docker with gid:1001
RUN addgroup --gid 1001 docker

# add user:pcluser to docker,pcluser group
RUN addgroup ${USERNAME} docker
# RUN addgroup ${USERNAME} ${USERNAME}

# expected result with: "id pcluser"
# uid=1000(pcluser) gid=1000(pcluser) groups=1000(pcluser),1001(docker)

# useful commands
# id
# id USER
# groups

# Optional
# Since I’m not familiar with Alpine Linux I had to investigate a little. 
# To have usermod and groupmod, I have to install the shadow package.
# https://cinhtau.net/2017/04/19/usermod-and-groupmod-alpine/

# change uid and gid for elasticsearch user
# RUN apk --no-cache add shadow && \
#     usermod -u 2500 elasticsearch && \
#     groupmod -g 2500 elasticsearch

# RUN useradd -m $USERNAME && \
#         echo "$USERNAME:1234" | chpasswd && \
#         usermod --shell /bin/zsh $USERNAME && \
#         usermod -aG sudo $USERNAME && \
#         echo "$USERNAME ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/$USERNAME && \
#         chmod 0440 /etc/sudoers.d/$USERNAME && \
#         usermod  --uid 1000 $USERNAME && \
#         groupmod --gid 1000 $USERNAME
# USER $USERNAME
FROM alpine:3.15 AS base
RUN apk add --no-cache sudo
ARG USERNAME=alpinedev
RUN adduser --gecos "$USERNAME" \
--disabled-password \
--shell /bin/sh \
--uid 1000 \
${USERNAME} && \
echo "$USERNAME:1234" | chpasswd && \
echo "$USERNAME ALL=(ALL) ALL" > /etc/sudoers.d/$USERNAME && chmod 0440 /etc/sudoers.d/$USERNAME
# creates a group: docker with gid:1001
RUN addgroup --gid 1001 docker
# add user:alpinedev to ["docker","alpinedev","wheel"] groups
RUN addgroup ${USERNAME} docker
RUN addgroup ${USERNAME} wheel
RUN addgroup ${USERNAME} ${USERNAME}
USER ${USERNAME}
# expected result with: "id alpinedev"
# uid=1000(alpinedev) gid=1000(alpinedev) groups=10(wheel),1000(alpinedev),1001(docker)
@goodnewsj62
Copy link

Nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment