かなりハマったので、メモ
参考:Copying non-root owned files between stages fails when running with userns remapping
条件
- docker version: 18.09.3
- Dockerの設定でユーザネームスペースのリマッピング("userns-remap": "default")を設定している
- Docker multi stage build を利用して、build間でファイルコピーを行う
例
例えば、次のようなDockerfileを考える
Dockerfile
FROM debian:stretch-slim as build
RUN touch x && chown 1000:1000 x
FROM debian:stretch-slim
COPY --from=build x ./
実行する
$ docker build ./
Sending build context to Docker daemon 3.072kB
Step 1/4 : FROM debian:stretch-slim as build
---> c08899734c03
Step 2/4 : RUN touch x && chown 1000:1000 x
---> Using cache
---> a2a3dcbc80a8
Step 3/4 : FROM debian:stretch-slim
---> c08899734c03
Step 4/4 : COPY --from=build x ./
failed to copy files: failed to copy file: Container ID 232072 cannot be mapped to a host ID
解法
コピー元のファイル、またはフォルダの権限をroot:rootに一時的に設定しておく。
Dockerfile
FROM debian:stretch-slim as build
RUN touch x && chown 1000:1000 x
RUN chown -R root:root x
FROM debian:stretch-slim
COPY --from=build x ./
$ docker build ./
Sending build context to Docker daemon 3.072kB
Step 1/5 : FROM debian:stretch-slim as build
---> c08899734c03
Step 2/5 : RUN touch x && chown 1000:1000 x
---> Using cache
---> a2a3dcbc80a8
Step 3/5 : RUN chown -R root:root x
---> Running in c018204a080d
Removing intermediate container c018204a080d
---> 64253585d0c5
Step 4/5 : FROM debian:stretch-slim
---> c08899734c03
Step 5/5 : COPY --from=build x ./
---> Using cache
---> 42d641d12386
Successfully built 42d641d12386