What is FROM in Dockerfile: Explanation and Usage
FROM instruction in a Dockerfile specifies the base image to start building your Docker image from. It sets the starting point for all subsequent instructions and is required as the first instruction in every Dockerfile.How It Works
The FROM instruction tells Docker which existing image to use as the foundation for your new image. Think of it like choosing a blank canvas before painting. This base image can be a minimal operating system, a language runtime, or any pre-built environment.
When you run a Docker build, Docker downloads this base image if it is not already on your machine. Then, it applies the rest of the instructions in the Dockerfile on top of this base, layering your customizations step by step. Without FROM, Docker wouldn't know where to start.
Example
This example shows a simple Dockerfile that uses FROM to start from an official Python image and then adds a script.
FROM python:3.11-slim COPY hello.py /app/hello.py CMD ["python", "/app/hello.py"]
When to Use
Use FROM whenever you create a Dockerfile to define the base environment for your application. It is essential for:
- Starting from a minimal OS like Alpine Linux for small images.
- Using language-specific images like Node.js, Python, or Java to simplify setup.
- Building multi-stage Dockerfiles by specifying multiple
FROMinstructions to optimize image size.
Choosing the right base image with FROM helps ensure your container has the necessary tools and libraries to run your app efficiently.
Key Points
FROMmust be the first instruction in a Dockerfile.- It defines the base image your container builds upon.
- You can use official images or custom images as the base.
- Multi-stage builds use multiple
FROMinstructions. - Choosing a lightweight base image can reduce your final image size.
Key Takeaways
FROM sets the base image for your Docker build and is required in every Dockerfile.FROM instructions to optimize images.