docker go permission works on mac fails on linux

Viewed 71

I'm trying to run go tests inside a container and want the coverage file exported to the host volume. My solution works on macOS but fails on linux.

my Dockerfile looks something like this:

FROM golang:1.17.9 AS codebase
WORKDIR /usr/src
COPY go.mod go.sum ./
RUN go mod download && go mod verify
COPY . .

FROM codebase AS builder
RUN go build -o ./myapp .

FROM alpine AS myapp
COPY --link --from=builder ./myapp ./
ENTRYPOINT [ "./myapp" ]

I run unit tests on the codebase stage that also generates the coverage file. I use docker compose for this. the docker-compose files looks like this:

version: "3.5"

services:
  unittest:
    container_name: unittest
    build:
      context: .
      target: codebase
    command: [go, test, "-failfast", "-coverprofile=/usr/mount/coverage.txt", "./..."]
    working_dir: /usr/src
    volumes:
      - ./:/usr/mount

Now, to execute the tests, I have this in Makefile:

docker compose build unittest
docker compose run unittest
ls -la coverage.txt
whoami
# ... do stuff with the coverage.txt file

Now on my local mac, the tests completes successfully and the coverage.txt has permission of my user (non root). ls output looks like this:

ls -la coverage.txt
-rw-r--r--  1 kanaksinghal  staff  3337 25 Jun 13:21 coverage.txt
whoami
kanaksinghal

But when I push this, and azure pipeline is triggered, the coverage file gets generated with root user and group:

ls -la coverage.txt
-rw-r--r-- 1 root root 3337 Jun 25 07:09 coverage.txt
whoami
vsts

I tried adding the --user flag to the docker compose run command but that makes the test fail both on local and in pipeline. Causing permission issues inside the container.

# docker compose run --user $(shell id -u):$(shell id -g) unittest
docker compose run --user 1001:121 unittest

failed to initialize build cache at /.cache/go-build: mkdir /.cache: permission denied

I'm trying to understand how come the coverage.txt file is not generated as root user on my mac. And can I make it behave the same way on pipeline.

I know I can change the file permission later after the docker run. But in other commands, I'm intending to use the same strategy to generate various other files as well so it'll be hard to change user then.

0 Answers
Related