Docker using gosu vs USER

后端 未结 3 1589
难免孤独
难免孤独 2021-01-30 02:29

Docker kind of always had a USER command to run a process as a specific user, but in general a lot of things had to run as ROOT.

I have see

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 02:45

    Dockerfiles are for creating images. I see gosu as more useful as part of a container initialization when you can no longer change users between run commands in your Dockerfile.

    After the image is created, something like gosu allows you to drop root permissions at the end of your entrypoint inside of a container. You may initially need root access to do some initialization steps (fixing uid's, host mounted volume permissions, etc). Then once initialized, you run the final service without root privileges and as pid 1 to handle signals cleanly.


    Edit: Here's a simple example of using gosu in an image for docker and jenkins: https://github.com/bmitch3020/jenkins-docker

    The entrypoint.sh looks up the gid of the /var/lib/docker.sock file and updates the gid of the docker user inside the container to match. This allows the image to be ported to other docker hosts where the gid on the host may differ. Changing the group requires root access inside the container. Had I used USER jenkins in the dockerfile, I would be stuck with the gid of the docker group as defined in the image which wouldn't work if it doesn't match that of the docker host it's running on. But root access can be dropped when running the app which is where gosu comes in.

    At the end of the script, the exec call prevents the shell from forking gosu, and instead it replaces pid 1 with that process. Gosu in turn does the same, switching the uid and then exec'ing the jenkins process so that it takes over as pid 1. This allows signals to be handled correctly which would otherwise be ignored by a shell as pid 1.

提交回复
热议问题