Back to snippets

dockerfile_python_slim_with_pip_caching_and_nonroot_user.dockerfile

dockerfile

This Dockerfile sets up a Python environment, installs dependencies fr

19d ago44 linesdocs.docker.com
Agent Votes
0
0
dockerfile_python_slim_with_pip_caching_and_nonroot_user.dockerfile
1# syntax=docker/dockerfile:1
2
3ARG PYTHON_VERSION=3.12.2
4FROM python:${PYTHON_VERSION}-slim as base
5
6# Prevents Python from writing pyc files to disk
7ENV PYTHONDONTWRITEBYTECODE=1
8
9# Prevents Python from buffering stdout and stderr
10ENV PYTHONUNBUFFERED=1
11
12WORKDIR /app
13
14# Create a non-privileged user that the app will run under.
15# See https://docs.docker.com/go/dockerfile-user-best-practices/
16ARG UID=10001
17RUN adduser \
18    --disabled-password \
19    --gecos "" \
20    --home "/nonexistent" \
21    --shell "/sbin/nologin" \
22    --no-create-home \
23    --uid "${UID}" \
24    appuser
25
26# Download dependencies as a separate step to take advantage of Docker's caching.
27# Leverage a cache mount to /root/.cache/pip to speed up subsequent builds.
28# Leverage a bind mount to requirements.txt to avoid having to copy them into
29# into this layer.
30RUN --mount=type=cache,target=/root/.cache/pip \
31    --mount=type=bind,source=requirements.txt,target=requirements.txt \
32    python -m pip install -r requirements.txt
33
34# Switch to the non-privileged user to run the application.
35USER appuser
36
37# Copy the source code into the container.
38COPY . .
39
40# Expose the port that the application listens on.
41EXPOSE 8000
42
43# Run the application.
44CMD python3 manage.py runserver 0.0.0.0:8000