UPX IMAGE

Sybren Boland
3 min readSep 10, 2021

--

Do you want smaller images with a faster startup time? Use UPX to compress your executable inside your image. Use a UPX image!

For more information on the internals of UPX take a look at their website here. Or at the source code of UPX here.

We will use an existing project from a previous post on native images. We will take this small image and make it even smaller.

Starting image

The project contains a maven build that produces an executable jar. In the Dockerfile we create a native image from this jar and copy it into the image.

# Copy the shaded application jar file to the build directory
COPY target/grpc-cat-api-*.jar /home/build/
# Create the native image executable
RUN native-image -jar grpc-cat-api-*.jar && mv grpc-cat-api api

From the previous post we saw that we have an image of 77.2MB with a startup time of 27ms.

UPX

To use UPX we first have to install it and compress the executable after it is copied into the image.

# Install UPX
RUN microdnf update -y oraclelinux-release-el8 && microdnf --enablerepo ol8_codeready_builder install xz && microdnf clean all && \
curl --location --output upx-3.96-amd64_linux.tar.xz "https://github.com/upx/upx/releases/download/v3.96/upx-3.96-amd64_linux.tar.xz" && \
tar -xJf upx-3.96-amd64_linux.tar.xz && \
cp upx-3.96-amd64_linux/upx /bin/
# Copy the shaded application jar file to the build directory
COPY target/grpc-cat-api-*.jar /home/build/
# Create the native image executable
RUN native-image -jar grpc-cat-api-*.jar && mv grpc-cat-api api
# Compress executable with UPX
RUN upx --best --lzma api

Notice that we install the dependencies, download UPX and extract it. This is just in the building image and will not effect the final image.

Results

Lets build and run the image and see wat we have gained…

docker build -t grpc-cat-api:1.0.1 .

Wow! We have an image of 31MB with a startup time of 17ms. Nice!

Hopefully you are now able to use UPX to compress your executable into a UPX image. Happy compressing!

--

--