Created
July 12, 2022 02:49
-
-
Save WoozyMasta/2d129f96b0823a2b36b1fae6be111c76 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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