Fixed "python image runs with root as the default user"

Added non-root user creation** (`appuser` with UID/GID 1000) - **Set
proper file ownership** for all application directories - **Switched
container execution** to non-root user with `USER appuser` - **Fixed
permission issues** for static files directory
This commit is contained in:
Marko Milić 2025-11-14 12:55:08 +01:00
parent 36993b64a4
commit edde7e05bb
3 changed files with 25 additions and 9 deletions

View File

@ -1,4 +1,9 @@
FROM python:3.10
# Create non-root user
RUN groupadd --gid 1000 appuser \
&& useradd --uid 1000 --gid appuser --shell /bin/bash --create-home appuser
COPY requirements.txt /app/
COPY apimanager/ /app/apimanager/
COPY static/ /app/static/
@ -7,6 +12,11 @@ COPY .github/local_settings_container.py /app/apimanager/apimanager/local_settin
RUN pip install -r /app/requirements.txt
WORKDIR /app
RUN ./apimanager/manage.py migrate
# Set proper ownership and switch to non-root user
RUN chown -R appuser:appuser /app
USER appuser
WORKDIR /app/apimanager
EXPOSE 8000
CMD ["gunicorn", "--bind", ":8000", "--config", "../gunicorn.conf.py", "apimanager.wsgi"]

View File

@ -1,5 +1,9 @@
FROM python:3.10
# Create non-root user
RUN groupadd --gid 1000 appuser \
&& useradd --uid 1000 --gid appuser --shell /bin/bash --create-home appuser
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
@ -29,14 +33,20 @@ COPY demo/ /app/demo/
COPY gunicorn.conf.py /app/
# Create necessary directories
RUN mkdir -p /app/logs /app/static /app/db
RUN mkdir -p /app/logs /app/static /app/db /static-collected
# Copy development local settings and entrypoint script to /usr/local/bin
COPY development/local_settings_dev.py /usr/local/bin/local_settings_dev.py
# Copy development local settings directly to the correct location
COPY development/local_settings_dev.py /app/apimanager/apimanager/local_settings.py
# Copy entrypoint script to /usr/local/bin
COPY development/docker-entrypoint-dev.sh /usr/local/bin/docker-entrypoint-dev.sh
# Set proper permissions
RUN chmod +x /app/apimanager/manage.py /usr/local/bin/docker-entrypoint-dev.sh
# Set proper permissions and ownership
RUN chmod +x /app/apimanager/manage.py /usr/local/bin/docker-entrypoint-dev.sh \
&& chown -R appuser:appuser /app \
&& chown -R appuser:appuser /static-collected
# Switch to non-root user
USER appuser
# Expose port
EXPOSE 8000

View File

@ -5,10 +5,6 @@
set -e
# Copy development local settings if it doesn't exist or force override
echo "Setting up development local_settings.py..."
cp /usr/local/bin/local_settings_dev.py /app/apimanager/apimanager/local_settings.py
# Wait for database to be ready
echo "Waiting for database to be ready..."
while ! pg_isready -h 127.0.0.1 -p 5434 -U apimanager -q; do