Transparent user permissions using devcontainers

Docker

Requirements

Lets say our docker image/devcontainer setup has the following requirements:

  1. a default username – user – that can be used by all host users
  2. user must have permissions to modify the local project files within the container, without modifying the host files ownership.
  3. user must have sudo access
  4. user must have passwordless sudo access

Solution

  1. We can add a generic user in our Dockerfile. Set the default user with the USER keyword.
  2. The devcontainer extension will “automatically update the container users UID/GID to match your local user to avoid the bind mount permissions problem”
  3. Use the Dockerfile to install sudo.
  4. Use the Dockefile to add our user to the /etc/sudoers file

Example files

.devcontainer/
├── devcontainer.json
└── Dockerfile

Dockerfile

FROM ubuntu:22.04

# this is our generic user
ARG USER=builder

# sudo for command line use
# git for vscode source control backend
RUN apt update -y && \
    DEBIAN_FRONTEND=noninteractive apt install -y \
    sudo \
    git 

# add the generic user with same group/password for simplicity
RUN useradd -m USER && echo "USER:USER" | chpasswd && adduserUSER sudo
# allow password-less sudo use
RUN echo "USER           ALL = (ALL) NOPASSWD: ALL" >> /etc/sudoers

# set our generic user as default
USERUSER  

# default command
CMD /bin/bash

.devcontainer.json

{
    // rebuild the image using local Dockerfile
    "build": {"dockerfile": "Dockerfile"},
    "customizations": {
        "vscode": {
            "settings": {
                // always default to bash not sh
                "terminal.integrated.defaultProfile.linux": "bash"
            }
        }
    }
}

Notes

  • Tested on Ubuntu 22.04

  • If you have problems try deleting the docker image created by devcontainer. This usually begins with vsc-<your-project-name>

Leave a Reply

Your email address will not be published. Required fields are marked *