Docker - Multi-Stage Build
Docker - Multi-Stage Build
Earlier, when we were building image for simple hello_world app, we used single-
stage build. Meaning, we were creating a single image from our Dockerfile. In this
build, our Image size was around 1.15 GB.
Big Docker Image size is not a good practice because docker images with big size
would be slow, more potential vulnerabilities and bigger attack service.
We can use the technique i.e. Multi-Stage Build to reduce the image size
significantly. In this technique, we only keep that stuff in the image which needs to
run the application in production.
For multi-stage build, the docker file would have multiple ‘FROM’ instructions. We
can do the heavy-lifting work of building the app in a large image with all the
compilers and other build tools required. We can then copy the final production app
into a tiny image used for production.
Here is the example of the multi-stage build for the same app we used above.
You can see the significant difference in the size. Great thing about this is, it works in
the container.
Next Steps:
Now we have to multi-stage build for todo_app we developed with FastAPI &
SQLModel using PostgreSQL. The problem we’ll encounter in that is the .env file.
We’ve created our environment variables i.e. DATABSE_URL and
TEST_DATABSE_URL in that file. Our todo_app needs those which I think can be
easily resolved by Docker Compose which we’ll study in upcoming classes.