How to run an nginx container as non root?

11,570

Solution 1

Use the rootless docker-imager from nginx.

Image

nginxinc/nginx-unprivileged  

DockerHub
https://hub.docker.com/r/nginxinc/nginx-unprivileged

GitHub
https://github.com/nginxinc/docker-nginx-unprivileged

Solution 2

You can remove (or comment) the user directive at the top of your nginx.conf file.

This directive is relevant when you run nginx as root. It defines the user possessing the pid of your nginx subprocesses.

When you don't run nginx as root this directive is irrelevant, your nginx subprocesses run with your current user.

Share:
11,570
Anonymous
Author by

Anonymous

Updated on July 27, 2022

Comments

  • Anonymous
    Anonymous almost 2 years

    Every time I try to run the container as non root, I get the following error:

     the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:2
    

    Dockerfile:

    FROM nginx:1.17.6
    RUN chown -R nginx:nginx /var/cache/nginx && \
            chown -R nginx:nginx /var/log/nginx && \
            chown -R nginx:nginx /etc/nginx/conf.d
    RUN chmod -R 777 /etc/nginx/conf.d
    
    USER nginx
    
    COPY app/build /usr/share/nginx/html
    
    RUN rm /etc/nginx/conf.d/default.conf
    
    COPY nginx/nginx.conf /etc/nginx/conf.d
    
    
    CMD ["nginx","-g","daemon off;"]
    
  • akop
    akop over 3 years
    I don't know why, but nginx has two official repos. The unprivileged image on GitHub was posted by the official nginx-GitHub.
  • burns0907
    burns0907 over 2 years
    how can i change the default nginx user to my own user? I can't do addgroup or adduser on top of this?
  • akop
    akop over 2 years
    You can do it in the Dockerfile with the USER-keyword.
  • burns0907
    burns0907 over 2 years
    it throws an error saying only root can add another user. sudo doesn't work and su asks for password
  • akop
    akop over 2 years
    Open a new question, then I can give you an example. :)
  • Sujit.Warrier
    Sujit.Warrier about 2 years
    This image has thorws up erros during trivy analysis, is there any alternative?
  • akop
    akop about 2 years
    Perhaps you want to open a new question about the errors. An alternative: Build an image yourself like Michée describes in his answer.