Running Nginx official image as non root

I’m confident this will guide you in deploying your application securely using Nginx.

To ensure security, we need to create a new user for Nginx with a specific user ID (UID), such as 1000. By default, Nginx runs as the root user, which has a UID of 1001.

In the Dockerfile, we’ll create this new user and grant it appropriate permissions. Then, we’ll switch to this user and expose a port greater than 1024, as root users can only bind to ports below 1024.

Afterward, we’ll update the nginx.conf file accordingly.

I’ll provide both files for you.

Dockerfile

FROM nginx:1.25.2

RUN apt-get update && apt-get install -y --no-install-recommends dumb-init

COPY ./nginx.conf /etc/nginx/nginx.conf

RUN adduser --system --uid 1000 --no-create-home --disabled-login --group nginxuser

RUN chown -R nginxuser:nginxuser /var/cache/nginx \
    && chown -R nginxuser:nginxuser /var/log/nginx \
    && chown -R nginxuser:nginxuser /etc/nginx/conf.d \
    && touch /var/run/nginx.pid \
    && chown -R nginxuser:nginxuser /var/run/nginx.pid

USER nginxuser

EXPOSE 8080

ENTRYPOINT ["dumb-init", "nginx", "-g", "daemon off;"]

nginx.conf

worker_processes 1;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    client_body_temp_path /tmp/client_temp;
    proxy_temp_path       /tmp/proxy_temp_path;
    fastcgi_temp_path     /tmp/fastcgi_temp;
    uwsgi_temp_path       /tmp/uwsgi_temp;
    scgi_temp_path        /tmp/scgi_temp;

    server {
        listen       8080;
        server_name  localhost;

        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
            try_files   $uri $uri/ /index.html =404;
        }
    }
}