We can have tons of docker images that could take plenty of our space. Let's see how we can optimize our docker images a bit.

Until now we’re pretty familiar on how Docker works in real life.

Just like git, we could’ve a similar sort of .dockerignore file which we can use exactly the same as .git file to list the files and folders we want to ignore while building the docker image.

There’s this simple snippet which we can use to optimize docker images:

FROM python:3.8-alpine

RUN mkdir /app

COPY requirements.txt requirements.txt

RUN apk add --no-cache --virtual .build-deps \
    && pip install -r requirements.txt \
    && find /usr/local \
        \( -type d -a -name test -o -name tests \) \
        -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
        -exec rm -rf '{}' + \
    && runDeps="$( \
        scanelf --needed --nobanner --recursive /usr/local \
                | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \
                | sort -u \
                | xargs -r apk info --installed \
                | sort -u \
    )" \
    && apk add --virtual .rundeps $runDeps \
    && apk del .build-deps

COPY . .

LABEL maintainer=" Usama Munir <usama@devpeel.com>" \

VOLUME ["/app/public"]

CMD flask run --host= --port=5000

Let’s build this image likeso:

docker image build -t weboptimized .

Now if we look at the results and compare this optimized image with the previously built image, the results are pretty good & we can use this approach for our production grade applications.

Almost half the size, cool isn’t it?

You may also Like