Update dependencies in the Dockerfile and create an image without re downloading the previously mentioned dependencies

Viewed 1724

Consider the following scenario. There is an application that depends on the libraries "A", "B", "C", to build and run, otherwise it throws an error. Not knowing about the dependencies "B", and "C" a Dockerfile is created that builds an image with the dependency "A" installed.

The app is run inside a container started from the image and the app fails to build, since the container is missing the dependencies "B" and "C".

Now if the image is destroyed and rebuilt, the previously downloaded dependencies will again be re-downloaded. A workaround could be to write a Dockerfile to import from the existing image (that has the dependency "A" installed) and mention the installation of the dependencies "B" and "C" on top of it.

But this way, Every-time a new dependency needs to be added a new docker image has to be built that will import from the old image, so, the old and the new image both remains important.

My question is that

  1. if there is any way to keep building images mentioning the new dependencies without re-downloding the old dependencies?
  2. without importing the dependencies from the old image ?
  3. and, without the hassle of writing a new "FROM" in the dockerfile?

What is the most clean solution for a scenario like this?

1 Answers

1. If there is any way to keep building images mentioning the new dependencies without re-downloading the old dependencies?

Well, i often optimize Dockerfile using layer caching. Whenever you write down a command in Dockerfile, it creates a new layer. Between 2 times build, docker compares the Dockerfile's commands top down and rebuild from where it detects command's changes. So i often put stable layers (like dependencies, environment setup) at the top of dockerfile. Otherwise layers like EXPOSE Port or CMD which i often change so i put them at bottom of the file. By doing this, it saves a lot of time whenerver i rebuild image.

You can also use multistage-build. But i not often use it so you can check it here: https://docs.docker.com/develop/develop-images/multistage-build/

2. without keeping the old image and import from that into the new one?

Sometime when i want to reinstall everything again, i just rebuild image use option --no-cache.**

docker build --no-cache=true .

3. Without the hassle of writing a new "FROM" in the dockerfile

Sometimes i use base image like linux alpine and install everything i need from scratch so my image will have smaller size and does not contain things that i dont need. FROM is just pulling images from Dockerhub which are created by the some way.

For example Dockerfile of image nginx-alpine : https://github.com/nginxinc/docker-nginx/blob/2ef3fa66f2a434cd5e44e35a02f4ac502cf50808/mainline/alpine/Dockerfile

You can checkout alpine linux for more details: https://alpinelinux.org/

Related