Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This account is not available: Unable to switch user in python alpine docker container

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.

like image 934
JPG Avatar asked Oct 28 '25 04:10

JPG


1 Answers

You're getting the This account is not available message because running adduser -S explicitly sets the shell for the account to /sbin/nologin (because you've asked for a system account with -S, the assumption is you don't expect interactive logins for this user).

You can explicitly set the shell for the named user:

/ # adduser -S -s /bin/sh jpg
/ # su - jpg
710ed667ddb2:~$ whoami
jpg

...or, as @tripleee suggests, just drop the -S from your adduser invocation and create a normal user; in this case, the shell will default to /bin/sh.

like image 76
larsks Avatar answered Oct 29 '25 20:10

larsks