How to run Docker-in-Docker in an alpine container as a non-root user?

Viewed 29

As the title says, I'm trying to run docker compose as a non-root user on an alpine container.

I have the following Dockerfile:

FROM docker.io/jenkins/ssh-agent:4.4.0-alpine-jdk17

# SSH public key
ENV JENKINS_AGENT_SSH_PUBKEY "ssh-key"

# Install Docker CLI
RUN apk add --no-cache docker-cli docker-cli-compose

# Add docker permissions to Jenkins user
COPY docker-perms.sh /docker-perms.sh
RUN delgroup ping && sh /docker-perms.sh

# I have to delete ping group as it has the same GID as docker

and docker-perms.sh:

#!/bin/sh
set -e
DOCKER_SOCKET=/var/run/docker.sock
RUNUSER=jenkins

if [ -S ${DOCKER_SOCKET} ]; then
    DOCKER_GID=$(stat -c '%g' ${DOCKER_SOCKET})
    DOCKER_GROUP=$(getent group ${DOCKER_GID} | awk -F ":" '{ print $1 }')
    if [ $DOCKER_GROUP ]
    then
        addgroup $RUNUSER $DOCKER_GROUP
    else
        addgroup -S -g ${DOCKER_GID} docker
        addgroup $RUNUSER docker
    fi
fi

I then mount the host's docker socket when I start the container. However, two things happen:

  1. I have to re-run docker-perms.sh as root inside the container because running docker ps as jenkins user returns the permission denied error. After running the script, it no longer produces an error

  2. When I run a job from the Jenkins controller, the permission denied error appears again anyway

What am I doing wrong?

1 Answers

I figured out what I was doing wrong: the docker.sock is only mounted after the image is built, so the script can't add the group.

This isn't a very pretty workaround, but I guess I can just add the group directly on the Dockerfile instead:

FROM docker.io/jenkins/ssh-agent:4.4.0-alpine-jdk17

# SSH public key
ENV JENKINS_AGENT_SSH_PUBKEY "ssh-key"

# Install Docker CLI
RUN apk add --no-cache docker-cli docker-cli-compose

# Add Docker permissions to Jenkins user
RUN DOCKER_GID=999 && \
    delgroup $(grep $DOCKER_GID /etc/group | cut -d: -f1) && \
    addgroup -S -g $DOCKER_GID docker && addgroup jenkins docker

This supposes that the docker group ID will be 999

Related