I'm working with Bazel to build an OCI image for a Python application, and I'm trying to configure it to run as a non-root user (mo1). While I've managed to specify this user in the Bazel oci_image rule, I'm encountering permission issues when the container runs.
oci_image(
name = "my_image",
base = "@python3_11",
entrypoint = ["python", "my_app.py"],
user = "mo1:mo1",
# Other configurations...
)
However, when running the container, the mo1 user doesn't seem to have the necessary permissions to execute certain files, leading to errors like:
/bin/sh: 1: /opt/services/metadata/metadata_bin.runfiles: Permission denied
So, how can I configure the oci_image in Bazel to set up a non-root user (mo1) and group, ensuring they have the correct permissions to access and run the application files?
I created this script create_user_and_group.sh
#!/bin/bash
set -e
WORKDIR="rootfs"
mkdir -p $WORKDIR/etc $WORKDIR/home/<some folder>
echo "mo1:x:1000:" > $WORKDIR/etc/group
echo "mo1:x:1000:1000::/home/<some folder>:/bin/bash" > $WORKDIR/etc/passwd
tar -czf accelerate_user_layer.tar -C $WORKDIR .
genrule(
name = "generate_user_layer",
srcs = ["create_user_and_group.sh"],
outs = ["user_layer.tar"],
cmd = "(./$(location create_user_and_group.sh) && cp user_layer.tar $(location user_layer.tar))",
visibility = ["//visibility:public"],
)
Using
rules_dockerIt seems that
rules_dockerhad support for this. The functionality for this is now moved torules_distroless.The old way via
rules_docker(tested with Bazel 7.0.2):Add to your
WORKSPACE.bazelfile:Note: rules_docker is deprecated now and there is no support for Bzlmod (at least it is not supported by BCR). Nevertheless, Bazel 7.x still supports the traditional
WORKSPACEapproach. Anyways we need only a few utility functions fromrules_docker.I tested a docker image build this way - but it seems not to be non-root. Maybe you get it working.
Using
rules_distorlessAdd to your
MODULE.bazelfilebazel_dep(name = "rules_distroless", version = "0.1.3")And to your
BUILD.bazelfile:Did also not work for me.
Switch to a nonroot image variant
I finally switched to a non-root base image. And this worked.