0

Can any one help me understand how can we Try to optimize the Dockerfile by removing all unnecessary cache/files to reduce the image size. and Removing unnecessary binaries/permissions to improve container security

My docker file look like this

FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP app.py
ENV FLASK_RUN_HOST 0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["flask", "run"]
Waseem Mir
  • 211
  • 3
  • 13

1 Answers1

1

Well, there is actually some ways to do that I guess:

  • multi-stage build
# STAGE1
FROM alpine AS stage1
WORKDIR /bin
RUN wget https://link/of/some/binaries -O app1 \
    && chmod +x app1 
# Run additional commands if you want

# STAGE2
FROM alpine AS stage2
WORKDIR /usr/local/bin
RUN wget https://link/of/some/binaries -O app2 \
    && chmod +x app2 
# Run additional commands if you want

# FINAL STAGE (runtime)
FROM python:3.7-alpine as runtime
COPY --from=stage1  /bin/app1 /bin/app1
COPY --from=stage2 /usr/local/bin/app2 /bin/app2
...

this will actually allow you to simply get only the binaries you need that you downloaded on the previous stages.

If you are using apk add and you don't know where things are getting installed you can try to test on an alpine image by running which command

  • remove cache
... # Install some stuff...

# Remove Cache
RUN rm -rf /var/cache/apk/*
Affes Salem
  • 1,303
  • 10
  • 26
  • 1
    Thanks Affes, to remove cache do I need to add this command at the end of my build file? – Waseem Mir Feb 12 '22 at 09:01
  • 1
    In my docker file is there any need of removing cache? as I am not installing `apt` or `apk` – Waseem Mir Feb 12 '22 at 09:42
  • 1
    Yes you have to specify it at the end since you want to reduce image size, or you could simply run `apk add --no-cache ...` on every installation you can find out more [here](https://stackoverflow.com/questions/49118579/alpine-dockerfile-advantages-of-no-cache-vs-rm-var-cache-apk), don't forget to consider upvoting my answer if it was helpful. – Affes Salem Feb 12 '22 at 11:16
  • 1
    you can also run this to remove tmp files `RUN rm -rf /tmp/*` – Affes Salem Feb 12 '22 at 12:57