Building Docker containers

We use GitLab CI/CD, to create our Python Docker containers.

  1. First, we define the Python version in our pyproject.toml file of the project:

    [project]
    name = "my-app"
    requires-python = "==3.12.*"
    
  2. We then extract this string in our .gitlab-ci.yml file and pass it as a build argument to docker build:

    build:
      stage: build
      only: [main]
      script:
        - export PY=$(sed -nE 's/^requires-python = "==(3\.[0-9]+)\.*"$/python\1/p' pyproject.toml)
        - >
          docker build
          --build-arg PY=$PY
    
  3. Finally, we can use the extracted version in the Dockerfile to create a virtual environment in the build phase and install the Python version in the application stage:

    FROM your-docker/build-image as build
    
    ARG PY
    RUN --mount=type=cache,target=/root/.cache \
        set -ex \
        && virtualenv --python $PY /app
    FROM your-docker/app-imageRUN set -ex \
        && apt-get update -qy \
        && apt-get install -qy \
            -o APT::Install-Recommends=false \
            -o APT::Install-Suggests=false \COPY --from=build --chown=app /app /app