In the previous section, we learned about what Docker is and how it can be used to containerize applications. Now, let's dive into creating a simple Dockerfile to build an image. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Using docker build, users can create an automated build that executes several command-line instructions in succession.
A Dockerfile consists of a series of instructions, each one creating a new layer in the image. The basic syntax for a Dockerfile is as follows:
Let's create a simple Dockerfile to build an image that runs a basic "Hello, World!" application using Python.
First, create a new directory for your project and navigate into it:
mkdir hello-world-dockercd hello-world-docker
Create a simple Python script that prints "Hello, World!".
1# app.py2print("Hello, World!")
Next, create a Dockerfile in the same directory. This file will contain instructions to build the Docker image.
1# Dockerfile2FROM python:3.9-slim34WORKDIR /app56COPY app.py .78CMD ["python", "app.py"]
/app.app.py file from your host machine into the /app directory in the container.Now that you have your Dockerfile and application ready, you can build the Docker image. Run the following command:
You should see the output:
Hello, World!
In this tutorial, we learned how to create a simple Dockerfile and build an image. In the next section, we will explore Multi-Stage Builds, which allow you to optimize your images by reducing their size and improving security.
Stay tuned for more advanced topics in our Docker curriculum!