Nginx Basic auth for private registry pull and push

When I was looking for a way to tell the Nginx to let all GET requests through the separate user list and all other requests (e.g. POST, PUT, etc) should be authenticated via the different user lists. This Nginx configuration allows restricting access via different methods to separate users.

This is very useful for the private docker registries, where you want every member of your team to be able to fetch Docker images, but only some users example admin, super admin to push new images to the registry.

Example:

  • User write team can use GET, POST, PUT, DELETE and everything else.
  • User read team can only use GET and HEAD.
  • Anonymous users are denied access entirely.
nginx-basic-auth-with-registry

Nginx-basic-auth-with-registry

We can use limit_except to configure this setup in Nginx.

Limits allowed HTTP methods inside a location.

Syntax: limit_except method ... { ... }

The method parameter can be one of the following: GET, HEAD, POST, PUT, DELETE, MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, or PATCH. Allowing the GET method makes the HEAD method also allowed.

Configure the Nginx authentication for the docker private registry pull user accounts and push user accounts using limit_except.

create docker pull users auth file.

# htpasswd -c /etc/nginx/.htpasswd_read read
update you password

read:$apr1$3WGzD7n7$nqa0h1K.8B/T7H23d64vM0

create docker pull/Push users auth file.

# htpasswd -c /etc/nginx/.htpasswd_write write
update you password

write:$apr1$3WGzD7n7$nqa0h1K.8B/T7H23d64vM0

Add these settings on your nginx config v2 location for the docker registry v2 setup. see the example of how to set up a private Docker registry with Nginx.

# vi nginx.conf

location /v2/ {
auth_basic "read";
auth_basic_user_file /etc/nginx/.htpasswd_read;
limit_except GET {
auth_basic "write";
auth_basic_user_file /etc/nginx/.htpasswd_write;
}
proxy_pass http://docker-registry;
}

 

Now you can test docker registry pull and push using your read, write users.