简体   繁体   中英

How to make VSCode terminal log in as a non-root user when attaching to an existing remote container

I created several containers for all members of my group based on a custom image. The purpose is to use them as development environments. All the containers run with tail -f /dev/nul command to make them permanent even if exit command is used, and they all have custom names based on the names of members of my group ( ${USER}_container ). We attach to them by using

docker exec -it --user $(id -u):$(cut -d: -f3 < <(getent group mygroup)) ${USER}_container bash

In this way every user appears as a member of "mygroup" user group within containers, which means that there is no problem with file ownership and permissions when using joint project bind mounts.

This works perfectly from within a terminal, but I'd also like for us to use VSCode for development. However, when I attach to one of the remote containers through VSCode and open a shell, it gives me the default one where a user is automatically root. It is quite important that this is not happening and that we are all logged in with our specific UIDs and GIDs.

I found "docker.command.attach" setting in VSCode settings and have changed it to the one we're using above, but it didn't help. How to tell VSCode to attach to a container the way we want to, and to open remote shells with custom UIDs and GIDs?

Found a brute-force workaround.

I added a specific user directly in the Dockerfile (first defining the group they belong to):

RUN groupadd --gid $GID $GROUPNAME
RUN useradd --uid $UID --gid $GID -m $USERNAME

and then in the docker-compose added the following line under all services I wanted to log in to with that specific UID/GID:

user: $USERNAME

For docker-compose I first needed to export the username explicitely before building my containers:

export USERNAME="Max Mustermann"

(unless, of course, I planned on using my own local username, in which case just writing user: $USER without exporting anything is enough).

The reason for adding the user in the Dockerfile is to have user data listed in /etc/passwd so that VSCode can pick them up. An alternative to not having access to Dockerfile is to make a small shell script that is going to attach to the container as the default (root) user and add the desired UID/GID subsequently.

After this VSCode automatically attached to the container as that specific user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM