Как изменить Root User на Custom User в Dockerfile

Я пытался сделать всех пользователей в моем Dockerfile пользовательскими, так как при запуске collectstatic в моем приложении Django, я получаю сообщение об ошибке:

 [Errno 13] Permission denied: 

/code/static/admin/js/vendor/select2/i18n/pl.6031b4f16452.js.gz'

Я также хочу сделать это по соображениям безопасности.

В настоящее время, когда я запускаю >docker-compose exec web ls -l /code/static, я получаю:

total 16
drwxrwxrwx 1 root root  4096 Apr  5 05:42 admin
drwxrwxrwx 1 root root  4096 Sep 18 21:21 css
drwxrwxrwx 1 root root  4096 Sep 18 21:21 human
drwxrwxrwx 1 root root  4096 Sep 18 18:42 img
-rw-r--r-- 1 1234 1234 13091 Sep 18 21:21 staticfiles.json
drwxrwxrwx 1 root root  4096 Sep 18 21:21 transcribe

Вот мой Dockerfile:

# Pull base image
FROM python:3.11.4-slim-bullseye

# Set environment variables
ENV PIP_NO_CACHE_DIR off
ENV PIP_DISABLE_PIP_VERSION_CHECK 1
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV COLUMNS 80

#install Debian and other dependencies that are required to run python apps(eg. git, python-magic).
RUN apt-get update \
  && apt-get install -y --force-yes python3-pip ffmpeg git libmagic-dev libpq-dev gcc \
    && rm -rf /var/lib/apt/lists/*

# Set working directory for Docker image
WORKDIR /code/

# Install dependencies
COPY requirements.txt .
RUN pip install -r requirements.txt

# Copy project
COPY . .

# Create a custom non-root user
RUN useradd -m example-user

# Grant necessary permissions to write directories and to user 'celery-user'
RUN mkdir -p /code/media /code/static && \
    chown -R example-user:uexample-user /code/media /code/static


# Switch to the non-root user. All this avoids running Celery with root/superuser priviledges which is a security risk
USER example-user

Всякий раз, когда я перестраиваю свой Dockerfile в соответствии с примерами лучших практик Docker и собираю образ, я получаю успешную сборку, но также несколько сообщений об ошибках.

Ошибка сборки 1:

=> CACHED [celery 5/8] WORKDIR /code/
=> CACHED [celery 6/8] COPY requirements.txt .
=> [celery 7/8] RUN pip install -r requirements.txt
=> => # WARNING: The script gunicorn is installed in '/home/example-user/.local/bin' which is not on PATH.
=> => # Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
=> => # WARNING: The script django-admin is installed in '/home/example-user/.local/bin' which is not on PATH.
=> => # Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
=> => # WARNING: The script celery is installed in '/home/example-user/.local/bin' which is not on PATH.
=> => # Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Ошибка сборки 2:

=> => transferring context: 49.55kB
=> CACHED [celery 2/8] RUN apt-get update  && apt-get install -y --force-yes python3-pip ffmpeg git libmagic-dev libpq-dev gcc  && r
=> CACHED [celery 3/8] RUN groupadd -g 1234 customgroupexample &&     useradd -m -u 1234 -g customgroupexample example-user
=> [celery 4/8] WORKDIR /code/
=> [celery 5/8] COPY requirements.txt .
=> [celery 6/8] RUN pip install -r requirements.txt
=> => # WARNING: The scripts cpack, ctest and cmake are installed in '/home/example-user/.local/bin' which is not on PATH.
=> => # Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
=> => # WARNING: The script normalizer is installed in '/home/example-user/.local/bin' which is not on PATH.
=> => # Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
=> => # WARNING: The script chardetect is installed in '/home/example-user/.local/bin' which is not on PATH.
=> => # Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Каталог /code не существует в dockerfile с пользователем в качестве владельца, поэтому он был создан как root. Решением стало изменение chmod каталога /code в dockerfile, удаление томов и повторный запуск compose up. Обновленный докерфайл:

# Pull base image
FROM python:3.11.4-slim-bullseye

# Set environment variables
ENV PIP_NO_CACHE_DIR off
ENV PIP_DISABLE_PIP_VERSION_CHECK 1
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV COLUMNS 80

#install Debian and other dependencies that are required to run python apps(eg. git, python-magic).
RUN apt-get update \
  && apt-get install -y --force-yes python3-pip ffmpeg git libmagic-dev libpq-dev gcc \
    && rm -rf /var/lib/apt/lists/*

# Set working directory for Docker image
WORKDIR /code/

# Create a non-root user
RUN useradd -m example-user

# Install dependencies
COPY requirements.txt .
RUN pip install -r requirements.txt

# Copy project
COPY . .



# Grant necessary permissions to write directories and to user 'example-user'
RUN mkdir -p /code/media /code/static \
  && chown -R example-user:example-user /code


# Switch to the non-root user. All this avoids running Celery with root/superuser priviledges which is a security risk
USER example-user

Обновленный compose.yml:

#version: "3.9"
services:
  web:
    build: .
    #command: python /code/manage.py runserver  0.0.0.0:8000
    command: gunicorn mysite.wsgi -b 0.0.0.0:8000 --reload
    volumes:
      - code_data:/code
    ports:
      - 8000:8000
...
volumes:
  postgres_data:
  code_data:
Вернуться на верх