Community for developers to learn, share their programming knowledge. Register!
Docker Images

Building Docker Images from Scratch


In this article, you can get training on building Docker images from scratch, focusing on a practical approach for intermediate and professional developers. Docker has revolutionized the way we deploy applications, and understanding how to create custom images is a vital skill for modern software development. This article will provide a thorough exploration of the process, from setting up prerequisites to creating a Dockerfile and running the build command, using Python as our primary example.

Prerequisites for Building Images

Before diving into building Docker images, ensure you have the following prerequisites:

  • Docker Installed: Make sure Docker is installed on your machine. You can download it from the official Docker website.
  • Familiarity with Docker Concepts: Understand fundamental Docker concepts like containers, images, and Dockerfiles. Familiarity with command-line interface (CLI) commands is also beneficial.
  • Basic Knowledge of Networking: Understanding how ports work and how to expose them in Docker will help you set up your application correctly.

Once you have these prerequisites in place, you’re ready to start building your Docker images.

Creating a Dockerfile

The Dockerfile is the heart of your Docker image. It defines the environment and the instructions needed to assemble your application. Below is a refined version of the Dockerfile based on the example you provided, which utilizes a Python Flask application.

# Use the official Python runtime as a parent image
FROM python:3.9-slim

# Set the working directory in the container
WORKDIR /usr/src/app

# Copy the current directory contents into the container at /usr/src/app
COPY . .

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "app.py"]

Explanation of the Dockerfile Instructions:

  • FROM: This instruction sets the base image for your application. Using python:3.9-slim ensures you have a lightweight Python environment.
  • WORKDIR: This command sets the working directory within the container. It is where all subsequent commands will be executed.
  • COPY: This command copies your application files from the host machine into the container. The dot (.) indicates that all files in the current directory will be copied.
  • RUN: The RUN command executes commands in a new layer on top of the current image and commits the results. Here, it installs the Python packages listed in requirements.txt.
  • EXPOSE: This indicates which port the application will listen on. In our example, port 80 is exposed, allowing external access.
  • ENV: This sets an environment variable, which can be used within your application. In this case, it's used to greet the user.
  • CMD: Finally, the CMD instruction specifies the command to run when the container starts, which is to execute app.py.

Example Project Structure

To give you a better understanding of how everything fits together, here’s a simple directory structure for your Python application:

/my-flask-app
│
├── app.py
├── Dockerfile
└── requirements.txt
  • app.py: This file would contain your Flask application logic.
  • requirements.txt: This file should list the required Python packages, such as Flask.

Here’s a simple example of what app.py might look like:

from flask import Flask
import os

app = Flask(__name__)

@app.route('/')
def hello():
    name = os.getenv('NAME', 'World')
    return f'Hello, {name}!'

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

When you run this Flask application inside a Docker container, it will greet users based on the NAME environment variable.

Running the Build Command

With your Dockerfile and application set up, it’s time to build your Docker image. Open your terminal, navigate to your project directory, and run the following command:

docker build -t my-flask-app .

Breakdown of the Command:

  • docker build: This is the command to create a Docker image from a Dockerfile.
  • -t my-flask-app: The -t flag tags the image with a name (in this case, my-flask-app). You can also add a version tag like my-flask-app:1.0.
  • .(dot): This indicates the build context, which is the current directory where Docker will look for the Dockerfile and any files to copy.

Running the Docker Container

Once the build completes successfully, you can run the container using the following command:

docker run -p 4000:80 my-flask-app

Explanation of the Command:

  • docker run: This command is used to create and start a container from the specified image.
  • -p 4000:80: This maps port 4000 on your host to port 80 in the container. You can now access your application by navigating to http://localhost:4000 in your browser.

Testing the Application

Once the container is running, you can test the application by visiting http://localhost:4000 in your web browser. You should see the message "Hello, World!" displayed on the page. If you want to customize the greeting, you can run the container with an environment variable like so:

docker run -p 4000:80 -e NAME=YourName my-flask-app

In this case, replacing YourName with any name of your choice will change the greeting displayed.

Summary

In this article, we explored the process of building Docker images from scratch, specifically tailored for a Python Flask application. We covered essential prerequisites, created a well-structured Dockerfile, and executed the build and run commands to deploy our application in a containerized environment.

Key Takeaways

  • Understanding Dockerfile: Knowing how to construct a Dockerfile is crucial for creating efficient and functional Docker images.
  • Docker Commands: Familiarity with Docker commands for building and running containers will streamline your development workflow.
  • Practical Application: The example provided demonstrates how to containerize a Python application, making it portable and easy to deploy.

With this foundational knowledge, you can now start creating your custom Docker images and deploying applications with ease. Dive deeper into the official Docker documentation for more advanced topics and best practices in Docker image creation.

Last Update: 15 Dec, 2024

Topics:
Docker