Learn to write a Dockerfile to create custom images with FROM, RUN, COPY, and CMD.
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. It's the recipe for building your Docker image. The process begins with a base image, specified using the `FROM` instruction. For example, you might start `FROM python:3.9-slim` to build a Python application. Subsequent instructions add layers on top of this base. The `RUN` command executes commands in a new layer, typically used for installing software packages (e.g., `RUN apt-get update && apt-get install -y git`). The `COPY` or `ADD` instructions are used to copy files and directories from your local machine into the image. `COPY` is generally preferred for its transparency. The `WORKDIR` command sets the working directory for any subsequent `RUN`, `CMD`, `ENTRYPOINT`, `COPY`, and `ADD` instructions. Finally, `CMD` or `ENTRYPOINT` specifies the command that will be executed when a container is started from the image. `CMD` provides a default command that can be easily overridden, while `ENTRYPOINT` configures a container that will run as an executable. A well-structured Dockerfile is key to creating efficient, secure, and maintainable images. It's crucial to follow best practices like minimizing the number of layers and cleaning up temporary files to keep image sizes small.