That's an excellent question, and it's a fundamental part of working with Docker!
You already provided a great example of what goes into it with your Dockerfile snippet. To build a custom Docker image, you generally follow these steps:
-
Create a Dockerfile:
This is a text file namedDockerfile(no file extension) that contains a series of instructions on how to build your image. Each instruction creates a new layer on top of the previous one.Your example
Dockerfileis perfect for this:FROM nginx RUN echo "Hello from custom layer" > /usr/share/nginx/html/hello.htmlFROM nginx: This is always the first instruction and specifies the base image your custom image will be built upon. Here, it uses the official Nginx image.RUN: This instruction executes any commands in a new layer on top of the current image and commits the results. In your case, it creates ahello.htmlfile inside the Nginx web root.
-
Save the Dockerfile:
Save thisDockerfilein an empty directory. It's a good practice to keep yourDockerfileand any related application files (like yourhello.htmlif it were a separate file) in a dedicated project directory. -
Use the
docker buildcommand:
Open your terminal, navigate to the directory where you saved yourDockerfile, and then run thedocker buildcommand:docker build -t my-custom-nginx .docker build: This is the command that Docker uses to build images from aDockerfile.-t my-custom-nginx: The-t(or--tag) flag allows you to give your new image a human-readable name and optionally a tag (version). Here, I've named itmy-custom-nginx. If you wanted to specify a version, you could domy-custom-nginx:v1.0..: This is crucial! It tells Docker to look for theDockerfilein the current directory. This path is also known as the "build context" – any files in this directory can be copied into your image during the build process.
When you run this command, Docker will execute each instruction in your
Dockerfile, creating a new layer for each step. You'll see output in your terminal as it progresses.
Once the build is complete, you can verify that your new image exists by running:
docker images
You should see my-custom-nginx listed there!
Does this explanation help you understand how to build your own Docker image? This is a more advanced topic than just pulling images, but it's where the real power of Docker customization comes in!