91

Can not create folder during image building with non root user added to sudoers group. Here is my Dockerfile:

FROM ubuntu:16.04

RUN apt-get update && \
    apt-get -y install sudo

RUN adduser --disabled-password --gecos '' newuser \
    && adduser newuser sudo \
    && echo '%sudo ALL=(ALL:ALL) ALL' >> /etc/sudoers

USER newuser

RUN mkdir -p /newfolder
WORKDIR /newfolder

I get error: mkdir: cannot create directory '/newfolder': Permission denied

Vadim Kovrizhkin
  • 1,575
  • 4
  • 16
  • 27

3 Answers3

86

Filesystems inside a Docker container work just like filesytems outside a Docker container: you need appropriate permissions if you are going to create files or directories. In this case, you're trying to create /newfolder as a non-root user (because the USER directive changes the UID used to run any commands that follow it). That won't work because / is owned by root and has mode dr-xr-xr-x.

Try instead:

RUN mkdir -p /newfolder
RUN chown newuser /newfolder
USER newuser
WORKDIR /newfolder

This will create the directory as root, and then chown it.

larsks
  • 277,717
  • 41
  • 399
  • 399
  • 1
    It helped. Thank you. But when i go to the container: docker exec -it img /bin/bash and then mkdir newfolder2 I get Permission denied and it requires 'sudo' command. Is it possible to do commands inside containers without 'sudo'? – Vadim Kovrizhkin Aug 07 '17 at 18:19
  • 2
    You used the `USER` directive, so when you run a command inside the container you are not `root`. If you want to be `root`, you need a privilege escalation tool such as `sudo` or `su`, or you need to redesign the container to not use the `USER` directive and consider instead something like an `ENTRYPOINT` script that will use `sudo` or similar to *drop* privileges when it runs your `CMD`. – larsks Aug 08 '17 at 21:20
21

Here is a process that worked for me to create folder as with non-user permissions

FROM solr:8
USER root
RUN mkdir /searchVolume
RUN chown solr:solr /searchVolume
USER solr

The last line drops the login back to solr (or whatever user you have).

Kahitarich
  • 395
  • 2
  • 7
-2

What worked for me is running chmod 777 on the directory that the docker container is in. Since your new container is a new user, it does not have permission to make sub directories on what would also be your local machine, so chmod 777 gives that permission