Docker Build Command: Create a Docker Image from Dockerfile

Docker Build Command Examples

Docker has become a cornerstone in today’s fast-paced development environments. It allows you to package your application, along with all its dependencies, into a container. This container can run anywhere, making deployment and scaling easier. The Dockerfile is at the heart of this process. It’s a simple text file that contains all the instructions needed to build a Docker image. The docker build command is essential for creating these images. It allows you to convert your Dockerfile into a runnable image.

In this article, we’ll explore creating a Docker image from a Dockerfile using the docker build command.

Understanding the Docker Build Command

The docker build is used to create an image from a Dockerfile. A Dockerfile is a text file that contains instructions for Docker to assemble an image. The basic syntax of the docker build command is:

 # docker build [OPTIONS] PATH | URL | -

Let’s break down this syntax:

  • OPTIONS: These are optional flags like -t for tagging the image, -f for specifying a Dockerfile, and –no-cache to build the image without using cached layers.
  • PATH: The location of the Dockerfile and context files. This can be a local directory or a remote URL.

Creating a Simple Python App

Follow the below steps to create a simple Python web application.

1. Create a directory for your app and navigate inside the directory:

 # mkdir my-python-app && cd my-python-app

2. Create a file named app.py.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=80)

3. Create a requirements.txt file and add the following content:

Flask

4. Create a Dockerfile and add the following.

FROM python:3.9-slim
WORKDIR /app
COPY . /app
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 80
CMD ["python3", "app.py"]

Let’s break down what each instruction does:

  • FROM: Use the official Python image as a base.
  • WORKDIR: Sets the working directory inside the container.
  • COPY: Copy the current directory contents into the container at /app.
  • RUN: Install the required Python packages.
  • EXPOSE: Expose port 80 for the application.
  • CMD: Define the command to run the application.

Building a Docker Image from the Dockerfile

Now that you have your Dockerfile, let’s build the Docker image.

1. Run the build command to create a Docker image.

 # docker build -t my-python-app .

This command will generate output as Docker steps through each line of the Dockerfile:

Sending build context to Docker daemon  7.68kB
Step 1/6 : FROM python:3.9-slim
 ---> fbf9f5c2f314
Step 2/6 : WORKDIR /app
 ---> Using cache
 ---> c3f485a26e17
Step 3/6 : COPY . /app
 ---> Using cache
 ---> 1341c65b3f89
Step 4/6 : RUN pip install --no-cache-dir -r requirements.txt
 ---> Running in 873d3bf8c6e5
Removing intermediate container 873d3bf8c6e5
 ---> e1b0f2b22b8b
Step 5/6 : EXPOSE 80
 ---> Using cache
 ---> 7603d99f7304
Step 6/6 : CMD ["python", "app.py"]
 ---> Using cache
 ---> 4c13bc2b48f6
Successfully built 4c13bc2b48f6
Successfully tagged my-python-app:latest

2. Verify the image was created:

 # docker images

This will show your new image in the list:

REPOSITORY          TAG       IMAGE ID       CREATED          SIZE
my-python-app       latest    4c13bc2b48f6   1 minute ago     125MB

Managing and Testing the Docker Image

1. Create a container from your my-python-app Docker image.

 # docker run -p 4000:80 my-python-app

This command starts the container and maps port 80 in the container to port 4000 on your host.

* Serving Flask app 'app.py'
* Running on http://0.0.0.0:80/ (Press CTRL+C to quit)

2. Open a web browser and go to http://localhost:4000. You should see “Hello, World!” displayed.

Pushing the Docker Image to a Docker Registry

Once your image is ready, you can push it to Docker Hub or any other registry.

1. Log in to Docker Hub:

 # docker login

Enter your Docker Hub credentials when prompted.

2. Tag your image:

 # docker tag my-python-app:latest yourdockerhubusername/my-python-app:latest

3. Push your image to the Docker registry.

 # docker push yourdockerhubusername/my-python-app:latest

This will upload your image to Docker Hub:

latest: digest: sha256:3bbd2f21a93be5c6b2db09f02ec42f76d393a7a7ef344e8c924e5940da7bc9f4 size: 1573

Understanding Docker Build Stages (Multi-stage Builds)

Multi-stage builds allow you to create smaller, optimized images by separating the build and runtime stages. This is especially useful for reducing image size.

Here’s an example Dockerfile for building a Go application using multi-stage builds:

# Build stage
FROM golang:alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o main .

# Runtime stage
FROM alpine
WORKDIR /app
COPY --from=builder /app/main .
CMD ["./main"]

In this example, the first stage compiles the Go application, and the second stage creates a minimal image that only includes the compiled binary. This approach significantly reduces the final image size.

Common Docker Build Options

Here are some commonly used options with the docker build command:

1. –build-arg: Pass build-time variables into the Dockerfile.

 # docker build --build-arg ENV=production -t my-app .

2. –target: Build a specific stage in a multi-stage Dockerfile.

 # docker build --target builder -t my-builder .

3. –rm: Remove intermediate containers after a successful build.

 # docker build --rm -t my-app .

Each of these options enables you to customize image creation based on your needs.

Conclusion

The docker build command is a powerful tool for creating Docker images tailored to your application’s needs. You now know how to create, build, and manage Docker images. Practice by creating Dockerfiles for your projects and push them to a registry. This will help you streamline your development and deployment processes.

FAQs

1. What does the -t option do in docker build?

The -t option tags the image with a name and optionally a version tag (e.g., my_image:latest).

2. How do I build a Docker image from a Dockerfile located in the current directory?

You can build an image from the current directory by specifying . as the build context.

3. What is the build context in the docker build command?

The build context refers to the files and directories specified in the path provided during the build. Docker uses these files for creating the image.

4. How do I view the build logs when creating a Docker image?

You can view the build logs using: docker build --progress=plain -t image_name.

About Hitesh Jethva

I am Hitesh Jethva, Founder and Author at Code2DevOps.com. With over 15 years of experience in DevOps and open source technologies, I am passionate about empowering teams through automation, continuous integration, and scalable solutions.

View all posts by Hitesh Jethva