Skip to content

Instantly share code, notes, and snippets.

@alekssamos
Forked from WoozyMasta/Dockerfile
Created October 2, 2022 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alekssamos/5005447135c8ccd0f614c52d53a39077 to your computer and use it in GitHub Desktop.
Save alekssamos/5005447135c8ccd0f614c52d53a39077 to your computer and use it in GitHub Desktop.
An example of building a Python application into a self-contained statically linked binary and packaging it into a container image based on scratch
FROM docker.io/python:3.9-bullseye AS build
WORKDIR "/app"
# Install dependecies
# hadolint ignore=DL3008,DL3013
RUN set -eux && \
apt-get update; \
apt-get install --no-install-recommends -y \
python3-dev build-essential patchelf upx; \
apt-get clean; \
rm -rf /var/lib/apt/lists/*; \
python -m pip install --no-cache-dir --upgrade --force --ignore-installed pip; \
python -m pip install --no-cache-dir --upgrade wheel staticx pyinstaller
# Copy scripts
RUN printf '%s\n' \
'#!/usr/bin/env python3' \
'import sys' \
'print("Hello world!")' \
'print(sys.version)' > hello-world.py
# Create Executable from Python Script with static linking and additional UPX
RUN set -eux && \
pyinstaller --name hw-compiled --onefile hello-world.py --paths "$(python -m site --user-site)"; \
staticx --strip dist/hw-compiled dist/hw; \
strip -s -R .comment -R .gnu.version --strip-unneeded dist/hw; \
rm dist/hw-compiled; \
mkdir -p dist/tmp
# Make app image
FROM scratch
COPY --from=build /app/dist/ /
ENTRYPOINT ["/hw"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment