DEV Community

Phui-Hock
Phui-Hock

Posted on

Building a non-root Docker container

Up until recently, I have been building container images with root and I run them as such, which is (of course) a very poor practice.

I started learning how to build non-root container a few days ago. In many examples, an arbitrary user is created. Files and directories are created and permissions are set with chmod. This makes Dockerfile slightly bloated with commands which make the image building process look like system administration.

The first question that comes to mind is, "Can't I use any one of the existing user in the container?" I opened up /etc/passwd in both ubuntu:18.04 and alpine:3.11, 2 base images that I commonly use. I found nobody, with id 65534 defined in both images.

Least privileged user? This is it.

I use Docker, VS Code with Remote Development extension for development. It allows me to attach to a running container and develop inside it. The source code is mounted into the container using bind mount.

Now, how do I save my files if the container runs as nobody while the source files on my host owned by me (another user)? It turns out that there is an (sort of) easy solution.

Dockerfile
---

from ubuntu:18.04
ENV HOME /app
USER nobody
WORKDIR ${HOME}
COPY src ./src/
ENTRYPOINT ["./src/helloworld.sh"]
docker-compose.yml
---

version: "3.7"

services:
    app:
        build:
            context: .
docker-compose.override.yml
---

version: "3.7"

services:
    app:
        user: "nobody:${GROUP}"
        volumes:
            - .:/app

With the files above in the project directory, the first step is to update the source folder with the group writable permission recursively, like so:

$ chmod -R g+wX <project dir>

Then, I run the container as the same group as the host user's group, like so:

$ GROUP=$(id -g) docker-compose up

Now, I can attach to the docker container from VS Code using Remote Development extension and develop inside it. When the image is deployed, it runs as nobody, which should be safer than running as root.

That said, I am still not sure if this is the best approach to non-root container. But this seems to work for my development workflow as well as deployment (with/without swarm mode)

Comments are welcomed.

Top comments (2)

Collapse
 
_kcbhaskar profile image
Bhaskar • Edited

Indeed a practical approach, In my opinion, running container as non priviledged user improves security too.

Collapse
 
dnk8n profile image
Dean Kayton

This seems like a very practical approach. I would also be interested in hearing other opinions.