Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docker can not write on mounted volume with non-root user

Tags:

docker

I have Dockerfile with myuser from nginx image and I want to mount logs on mounted location, I am using docker-compose to start the container. My requirement is to use non-root user only and no sudo.

My dockerfile with myuser, image tag I create is mynginx:v1

RUN addgroup mygroup
RUN adduser myuser --disabled-password
USER myuser

Non-Working docker compose with mynginx image with myuser

version: "2"
services:
  nginx:
    container_name: nginx
    image: mynginx:v1
    ports:
      - "8888:80"
    volumes:
      - ./log/nginx:/var/log/nginx

Although directory get mounted, nginx log files access.log and error.log are not seen on host machine.

Docker logs gives below:

nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (13: Permission denied)
2021/04/09 12:46:08 [warn] 1#1: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:2
2021/04/09 12:46:08 [emerg] 1#1: mkdir() "/var/cache/nginx/client_temp" failed (13: Permission denied)

However If I do the same with official nginx image which runs as root user, things work correctly.

Working docker compose with official nginx image with root user

version: "2"
services:
  nginx:
    container_name: nginx
    image: nginx
    ports:
      - "8888:80"
    volumes:
      - ./log/nginx:/var/log/nginx

Tried to look at various options but no luck so far.

like image 984
Learner Avatar asked Jan 17 '26 21:01

Learner


1 Answers

Most propably the UID on your host for myuser does not match the UID for myuser inside the Container.

Solution

If you want to write from within your container into a directory of your host machine you must first create a myuser User on your host and check its UID via

$ sudo su - myuser -c "id"
uid=1000(myuser) gid=100(users) Gruppen=100(users)

In this example UID=1000 and GID=100.

Now you will need to create a Folder ~/log/nginx with owner/group of myuser on your host.

$ sudo mkdir ~/log/nginx
$ sudo chown myuser ~/log/nginx
$ sudo chmod -R 0700 ~/log/nginx/

Afterwards you can create a Dockerfile and your user with the same UID/GID.

RUN useradd myuser -u 1000 -g 100 -m -s /bin/bash
USER myuser

Now you should be able to write to your mounted volume with the specified user. You can check this via:

docker run -v $(pwd)/log/nginx:/var/log/nginx --rm -it mynginx:v1 /bin/bash

if you can now write to /var/log/nginx

like image 135
A.K. Avatar answered Jan 19 '26 18:01

A.K.