If like me, you have difficulties to find a clear guide on how to create a Docker image in an app whose dependencies are managed via Poetry, this article is for you.
The goals are:
- to keep only the code useful to the runtime in the final image (not Poetry’s own dependencies or downloads).
- to reduce network consumption to a minimum when sending a new docker image to the registry.
To achieve this, the provided Docker file:
- enables the new Docker build system named via the environment variable DOCKER_BUILDKIT=1
- uses the multi-layer mechanism of Docker to separate the installation part from the execution part.
Bonus, you could use this Docker file to deploy with your FastAPI application with gunicorn (and uvicorn workers).
Each time a layer is modified in the Docker build, all next layers are invalidated so you lose the cache benefit. Over the course of the development, you will have to update your base image or dependencies so these cache invalidations will be inevitable but to avoid them, I choose set the most stable settings earlier as possible in the Dockerfile.