Junior — Middle
What steps should be taken to reduce the size of a Docker image?
sobes.tech AI
Answer from AI
To reduce the size of a Docker image, the following steps can be taken:
- Use minimal base images, such as
python:3.9-slimoralpineinstead of fullubuntuordebian. - Remove temporary files and caches after installing dependencies in one layer so they are not saved in the image.
- Combine RUN commands in the Dockerfile to reduce the number of layers.
- Use
.dockerignoreto exclude unnecessary files from the build context. - Minimize the number of packages and dependencies installed.
Example of Dockerfile optimization:
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]
This uses a slim image and the --no-cache-dir flag for pip to avoid saving caches in the image.