Cannot create directory. Permission denied inside docker container
Asked Answered
T

3

104

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

Testimony answered 7/8, 2017 at 18:4 Comment(0)
F
95

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.

Fiddlededee answered 7/8, 2017 at 18:8 Comment(2)
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'?Testimony
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.Fiddlededee
A
25

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

Arid answered 14/4, 2021 at 4:24 Comment(0)
N
-8

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

Navelwort answered 30/6, 2022 at 4:2 Comment(1)
Using chmod 777 is a significant security concern.Pondweed

© 2022 - 2024 — McMap. All rights reserved.