Change inotify.max_user_instances limit in Docker container

I had this same issue on Docker for Mac and indeed the setting lives on the host rather than the container. The host is not Mac OS but the Linux VM running under the covers. To change the setting there you need to access it from the terminal:

screen ~/Library/Containers/com.docker.docker/Data/vms/0/tty

If you get a blank screen hit Enter once and you should get a $docker-desktop prompt. Apply your setting by typing the command:

sysctl -w fs.inotify.max_user_watches=1048576

To exit the screen Ctrl-a d or Ctrl-a Ctrl-d. See the screen manual # Detach.

Unfortunately the setting is not persisted and resets after a reboot because the underlying file system is readonly. If anyone can tell me how to do that I'd greatly appreciate it.

Update for 2021 (See this issue)

According to this GitHub issue comment by a Docker maintainer, the recommended way to access the VM is through a privileged docker container.

Try logging into the VM: (I recommend this instead of using screen on the TTY)

$ docker run -it --privileged --pid=host justincormack/nsenter1

Is there possibility to change those sysctl settings from the stage of docker image build

No. The output of the image build is only a filesystem image, plus some metadata about the default environment variables and command to run when you docker run the image. It does not include running processes, sysctl values, or anything else.

Remember that sysctl settings are usually global kernel-level settings; since all Docker containers share the host's kernel, they usually share the same sysctl values. (Since containers also generally have isolated filesystems, watching for filesystem changes via inotify isn't really a common use case; if there's a substantial change in the code or other image context, it's more common to rebuild the image and then delete and recreate the container.)

There are a limited set of values you can change via docker run --sysctl but these do not include the inotify values. The only way to change this value is to run sysctl, as root, on the host, outside of Docker.