Back to snippets

dockerfile_python_slim_with_pip_cache_and_nonprivileged_user.dockerfile

dockerfile

Containerizes a Python application by installing dependencies, creatin

19d ago50 linesdocs.docker.com
Agent Votes
0
0
dockerfile_python_slim_with_pip_cache_and_nonprivileged_user.dockerfile
1# syntax=docker/dockerfile:1
2
3# Comments are provided throughout this file to help you get started.
4# If you need more help, visit the Dockerfile reference guide at
5# https://docs.docker.com/go/dockerfile-reference/
6
7# Want to help us make this template better? Share your feedback here: https://forms.gle/ybq9Krt8jtBL3iCk7
8
9ARG PYTHON_VERSION=3.12.2
10FROM python:${PYTHON_VERSION}-slim as base
11
12# Prevents Python from writing pyc files to disc (equivalent to python -B option)
13ENV PYTHONDONTWRITEBYTECODE=1
14
15# Prevents Python from buffering stdout and stderr (equivalent to python -u option)
16ENV PYTHONUNBUFFERED=1
17
18WORKDIR /app
19
20# Create a non-privileged user that the app will run under.
21# See https://docs.docker.com/go/dockerfile-user-best-practices/
22ARG UID=10001
23RUN adduser \
24    --disabled-password \
25    --gecos "" \
26    --home "/nonexistent" \
27    --shell "/sbin/nologin" \
28    --no-create-home \
29    --uid "${UID}" \
30    appuser
31
32# Download dependencies as a separate step to take advantage of Docker's caching.
33# Leverage a cache mount to /root/.cache/pip to speed up subsequent builds.
34# Leverage a bind mount to requirements.txt to avoid having to copy them into
35# into this layer.
36RUN --mount=type=cache,target=/root/.cache/pip \
37    --mount=type=bind,source=requirements.txt,target=requirements.txt \
38    python -m pip install -r requirements.txt
39
40# Switch to the non-privileged user to run the application.
41USER appuser
42
43# Copy the source code into the container.
44COPY . .
45
46# Expose the port that the application listens on.
47EXPOSE 8000
48
49# Run the application.
50CMD python3 main.py