HiveBrain v1.2.0
Get Started
← Back to all entries
snippetdockerMajor

How to change the owner of VOLUME directory in Dockerfile?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
ownerdirectorythedockerfilehowchangevolume

Problem

I've got the following Dockerfile:

FROM ubuntu:xenial
RUN useradd -d /home/ubuntu -ms /bin/bash -g root -G sudo -p ubuntu ubuntu
WORKDIR /home/ubuntu
USER ubuntu
VOLUME /opt/myvolume


Which I built it:

$ docker build -t vol-test .
Sending build context to Docker daemon  2.048kB
Step 1/5 : FROM ubuntu:xenial
 ---> 0b1edfbffd27
Step 2/5 : RUN useradd -d /home/ubuntu -ms /bin/bash -g root -G sudo -p ubuntu ubuntu
 ---> Using cache
 ---> d82e3ecc5fe8
Step 3/5 : WORKDIR /home/ubuntu
 ---> Using cache
 ---> ab1db29ee8bf
Step 4/5 : USER ubuntu
 ---> Using cache
 ---> 129393a35d9e
Step 5/5 : VOLUME /opt/myvolume
 ---> Running in 691a4cbd077e
Removing intermediate container 691a4cbd077e
 ---> 11bc9e9db9d3
Successfully built 11bc9e9db9d3
Successfully tagged vol-test:latest


However, when run, the /opt/myvolume directory is owned by root, not ubuntu:

$ docker run vol-test id
uid=1000(ubuntu) gid=0(root) groups=0(root),27(sudo)
$ docker run vol-test find /opt/myvolume -ls
    66659      4 drwxr-xr-x   2 root     root         4096 Jul 18 23:02 /opt/myvolume
$ docker run -u ubuntu vol-test find /opt/myvolume -ls
    66940      4 drwxr-xr-x   2 root     root         4096 Jul 18 23:12 /opt/myvolume


because it's created during the run.

Is it possible to define or change the default owner of VOLUME directory in Dockerfile?

I'm running it on macOS and Linux.

Solution

As stated in the documentation, VOLUME instruction inherits the directory content and permissions existing in the container, so you can workaround the problem with a dockerfile like this:

FROM ubuntu:xenial
RUN useradd -d /home/ubuntu -ms /bin/bash -g root -G sudo -p ubuntu ubuntu
RUN mkdir /opt/myvolume  && chown ubuntu /opt/myvolume
WORKDIR /home/ubuntu
VOLUME /opt/myvolume


The creation of the directory has to be done as root (to be able to write within /opt).

Code Snippets

FROM ubuntu:xenial
RUN useradd -d /home/ubuntu -ms /bin/bash -g root -G sudo -p ubuntu ubuntu
RUN mkdir /opt/myvolume  && chown ubuntu /opt/myvolume
WORKDIR /home/ubuntu
VOLUME /opt/myvolume

Context

StackExchange DevOps Q#4540, answer score: 27

Revisions (0)

No revisions yet.