Connect to docker container as user other than root

后端 未结 9 1029
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 01:38

BY default when you run

docker run -it [myimage]

OR

docker attach [mycontainer]

you connect to the terminal as r

相关标签:
9条回答
  • 2020-12-13 02:15

    For docker run:

    Simply add the option --user <user> to change to another user when you start the docker container.

    docker run -it --user nobody busybox
    

    For docker attach or docker exec:

    Since the command is used to attach/execute into the existing process, therefore it uses the current user there directly.

    docker run -it busybox  # CTRL-P/Q to quit
    docker attach <container id>  # then you have root user
    / # id
    uid=0(root) gid=0(root) groups=10(wheel)
    
    docker run -it --user nobody busybox # CTRL-P/Q to quit
    docker attach <container id>  
    / $ id
    uid=99(nobody) gid=99(nogroup)
    

    If you really want to attach to the user you want to have, then

    1. start with that user run --user <user> or mention it in your Dockerfile using USER
    2. change the user using `su
    0 讨论(0)
  • 2020-12-13 02:16

    For docker-compose. In the docker-compose.yml:

    version: '3'
    services:
        app:
            image: ...
            user: ${UID:-0}
    ...
    

    In .env:

    UID=1000
    
    0 讨论(0)
  • 2020-12-13 02:17

    As an updated answer from 2020. --user , -u option is Username or UID (format: <name|uid>[:<group|gid>]).

    Then, it works for me like this,

    docker exec -it -u root:root container /bin/bash
    

    Reference: https://docs.docker.com/engine/reference/commandline/exec/

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