Dynamically create an image with the host's user/uid

Build a Docker image whose user matches the host UID and GID to avoid file ownership problems.

1 min read Updated

Building an image that runs as a fixed user often leaves files owned by the wrong UID on the host. This script derives the host user's name and UID and injects them into the image at build time, so the container user matches the host. The script is reproduced below.

create-image-with-host-user.sh

bash
#!/bin/bash

set -u

user.id() {
  echo $UID
}

user.name() {
  set +u

  if [ -n "$USERNAME" ]; then
    echo $USERNAME # for Windows compatibility with Git Batch
  else
    echo $USER
  fi

  set -u
}

# generate the custom user's Dockerfile
read -r -d '' Dockerfile <<- EOM
  FROM alpine

  # here install what you need
  RUN apk update && \\
      apk add --no-cache wget

  RUN addgroup -S $(user.name) -g $(user.id) && \\
      adduser -S -G $(user.name) -u $(user.id) $(user.name)

  USER $(user.name)
EOM

# build the image
echo -e "$Dockerfile" | docker build -t toolbox -

Search articles

Type to filter articles. Use the arrow keys to move through results and Enter to open one. Press Escape to close.