1
+ # The dockerfile uses multi-stage builds to build the application
2
+ # and then copy the build artifacts to the final image. This helps for the layer optimization.
3
+ # https://docs.docker.com/develop/develop-images/multistage-build/
4
+ #
5
+ # Environment replacement
6
+ # - "PYTHONDONTWRITEBYTECODE 1": Python won’t try to write .pyc files on the import of source modules
7
+ # It make sense in a container, since the process runs just once.
8
+ #
9
+ # - "PYTHONUNBUFFERED 1": Force the stdout and stderr streams to be unbuffered. This option has no effect on the stdin stream.
10
+ # - "PIP_NO_CACHE_DIR 1": Disable pip cache, used to shrink the image size by disabling the cache.
11
+ #
12
+ # - PATH: defining virtual enviroment in /opt, since is used to reserved for the installation of add-on application software packages.
13
+ # This can help with with minimizing docker image size when doing multi-staged builds.
14
+ #
15
+ # WORKDIR: https://docs.docker.com/engine/reference/builder/
16
+ # - WORKDIR /app: set the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile.
17
+ # - we don't even need to run mkdir /app since WORKDIR will make it for us.
18
+ # - good practice because we can set a directory as the main directory
19
+ # "COPY . .": the contents of the build context directory will be copied to the /myapp dir inside your docker image.
20
+ # (COPY <src: "relative to the build context directory"> (TO) <dest: "relative to the WORKDIR directory">)
21
+
22
+ # ## build stage ###
23
+ FROM python:3.9 AS builder
24
+
25
+ WORKDIR /app
26
+
27
+ ENV PYTHONDONTWRITEBYTECODE 1
28
+ ENV PYTHONUNBUFFERED 1
29
+ ENV PIP_NO_CACHE_DIR 1
30
+ ENV PATH="/opt/venv/bin:$PATH"
31
+
32
+ RUN apt-get update && \
33
+ apt-get install -y --no-install-recommends gcc && \
34
+ python -m venv /opt/venv
35
+
36
+ COPY requirements.txt .
37
+ RUN pip install -r requirements.txt
38
+
39
+ # ## final stage ###
40
+ FROM python:3.9-slim
41
+
42
+ WORKDIR /app
43
+
44
+ ENV PATH="/opt/venv/bin:$PATH"
45
+
46
+ COPY --from=builder /opt/venv /opt/venv
47
+ COPY . .
0 commit comments