Running as a host user within a Docker container

后端 未结 3 930
抹茶落季
抹茶落季 2021-02-03 23:58

In my team we use Docker containers to locally run our website applications while we do development on them.

Assuming I\'m working on a Flask app at app.py

相关标签:
3条回答
  • 2021-02-04 00:35

    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.

    0 讨论(0)
  • 2021-02-04 00:43

    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)

    0 讨论(0)
  • 2021-02-04 00:50

    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.

    0 讨论(0)
提交回复
热议问题