Running as a host user within a Docker container Running as a host user within a Docker container flask flask

Running as a host user within a Docker container


You can share the host's passwd file:

docker run -ti -v /etc/passwd:/etc/passwd -u `id -u`:`id -g` -v `pwd`:`pwd` -w `pwd` -v pydeps:/usr/local -p 8000:8000 python:3-slim ./manage.py runserver

Or, add the user to the image with useradd, using /etc as volume, in the same way you use /usr/local:

docker run -v etcvol:/etc python..... useradd -u `id -u` $USER

(Both id -u and $USER are resolved in the host shell, before docker receive the command)


Just hit this problem and found a different workaround.

From getpass.py:

def getuser():    """Get the username from the environment or password database.    First try various environment variables, then the password    database.  This works on Windows as long as USERNAME is set.    """    for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):        user = os.environ.get(name)        if user:            return user    # If this fails, the exception will "explain" why    import pwd    return pwd.getpwuid(os.getuid())[0]

The call to getpwuid() is only made if none of the following environment variables are set: LOGNAME, USER, LNAME, USERNAME

Setting any of them should allow the container to start.

$ docker run -ti -e USER=someuser ...

In my case, the call to getuser() seems to come from the Werkzeug library trying to generate a debugger pin code.


If it's okay for you to use another Python package to start your container, maybe you want to use my Python package https://github.com/boon-code/docker-inside which overwrites the entrypoint and creates your user in the container on the fly...

docker-inside -v `pwd`:`pwd` -w `pwd` -v pydeps:/usr/local -e FLASK_APP=app.py -e FLASK_DEBUG=true -p 5000:5000 python:3-slim -- flask run -h 0.0.0.0

Overriding entrypoint on the command line and passing a script that creates your user might also be okay for you, if you want to stick with Docker CLI.