I have a simple Dockerfile
FROM python:3.10-alpine
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set arguments
ARG USERNAME=jpg
ARG USER_DIR=/home/$USERNAME
ARG WORK_DIR=$USER_DIR/app
# Creating a non-root user
RUN adduser -S $USERNAME
# Switching the user
USER $USERNAME
# Create a new directory to keep the project files
RUN mkdir $WORK_DIR
# Copy local contents into container
COPY ./ $WORK_DIR
# Setting newly created directory as PWD
WORKDIR $WORK_DIR
# Adding user's bin path to `PATH` variable
ENV PATH "$PATH:$USER_DIR/.local/bin"
# Installing pip packages
RUN pip install pip -U
I built the image using following command
docker build . -t test-img:latest
After the successfull image build, run the image using
docker run -i -t test-img:latest python
This gave me an interactive shell, as expected. Also, I tried to pull the user info using getuser(...)
function as well
Python 3.10.10 (main, Mar 14 2023, 03:01:12) [GCC 12.2.1 20220924] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import getpass
>>> getpass.getuser()
'jpg'
>>>
Then, I moved to another terminal and logged in to the same container as root
user. After logged-in, tried to switch the user to jpg
(which is defined within the Dockerfile
)
$ docker exec -it -u root f6dc515bca29 sh
/home/jpg/app # su - jpg
This account is not available
/home/jpg/app # su - "jpg"
This account is not available
/home/jpg/app # su -l "jpg"
This account is not available
/home/jpg/app # su -l jpg
This account is not available
/home/jpg/app #
Question
How can I switch the user to jpg
(or any non-root user) in an alpine-based container from root
?
Note: It is mandatory to log in as root (-u root
) in an exec
session because this is to simulate a situation of AWS Fargate containers.