This is the 4-line code for the simplest Docker image. BUT
- What is this
FROM scratch
? - Do we need a base image like
ubuntu
oralpine
? - What are the benefits of doing this ?
let's answer these all questions !
Lets clear the basics first
Running a Docker container means running the single application inside the Docker container. The single application is nothing but a process inside the host machine.
We use different base images, like ubuntu
and alpine
Because these images contain the files and dependencies which our application may require to run.
Ever wondered how the base images are made?
Every Docker image starts with an empty image called scratch
which is empty inside, meaning it has nothing inside it. The files and folders required are copied inside it.
Let's take an example of the base image 'ubuntu`.
linux directory example
all the directory structure are created and all the required files are copied inside the scratch
image and finally base image ubuntu
is created.
so, ubuntu
base image is nothing but a file & directory structures copied inside a scratch
image.
If your application requires nothing else than your application binary, then you can just copy the binary inside the scratch
base image and it will work. and this is what we are doing in the 4-line docker image file.
Answering the question.
- What is this
FROM scratch
?
Ans: scratch is a keyword in docker which tells docker that you are starting an empty image and you will copy files as required and nothing else than that.
- Do we need a base image like
ubuntu
oralpine
?
Ans: if your application doesnot depends on any files or programs inside these image than you donot require them, you can just start from
scratch
.
- What are the benefits of doing this ?
Ans: It minimizes the image size as much as possible. Additionally, since your Docker image includes only the necessary components, it reduces the risk of security vulnerabilities.
Things to remember
When you write your application in compiled languages like C
Rust
, Golang
you must compile it into a static binary
. Static binary refers to a binary of your application that does not require anything from the operating system and contains all the dependencies required by it. This allows the application to run independently. Read more here
Conclusion
You can use scratch
to create image of your application which will be super simplified, containing only the required components and nothing else which makes your image smaller and less prone to security issues.
Stay in touch where i keep posting technology related stuff
X.com : https://x.com/anisharaz
Top comments (3)
Great, sir I need this type of blog your knowledge is amazing
Cleared my doubt on base image and will try to use scratch to create image for my application.
Need hands on using scratch to create image for application.
fantastic