Cannot create directory. Permission denied inside docker container

UbuntuDockerSudoers

Ubuntu Problem Overview


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

Ubuntu Solutions


Solution 1 - Ubuntu

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.

Solution 2 - Ubuntu

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).

Solution 3 - Ubuntu

I actually had this problem after I had created a [root] user and done xyz. When I went to re-build my docker (even with force recreate), it was giving me all sorts of permission denied errors. Security wasn't an issue for me so simply adding

FROM ubuntu:latest

USER root

ENV TZ=Europe/Kiev
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

RUN apt-get update && apt-get install...

Then doing my new user code

RUN useradd...

I know this is not the perfect answer but I hope it helps!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVadim KovrizhkinView Question on Stackoverflow
Solution 1 - UbuntularsksView Answer on Stackoverflow
Solution 2 - UbuntuKahitarichView Answer on Stackoverflow
Solution 3 - Ubuntugmg13View Answer on Stackoverflow