Expertise

Docker has transformed the way we build, package, and deploy programs, making containerization easier than ever. While the concept of containerizing apps predates Docker, Docker's simplicity and usefulness have made it an indispensable tool in modern development workflows. Chances are, your dream organization is already using Docker to optimize operations.

However, navigating Docker's enormous documentation can be difficult, particularly for newcomers. The vast amount of knowledge available from numerous places might easily overwhelm you. But do not worry—creating Docker images does not have to be difficult.

In this post, we will walk you through the process of producing Docker build images. You'll learn how to create local docker images, use best practices, and confidently publish your images. 

What is Docker Build?

Docker Build is the most basic function of the Docker Engine, where developers can build container images based on their specific applications. In other words, Docker Build forms the core of containerization in the software development lifecycle, enabling the packaging of applications into portable and reusable images.

Docker Build can create images simply but is also powerful for managing complex workflow. From tiny applications to deployments at the scale of enterprises, Docker Build provides developers with automated image creation to ensure uniform settings in development, testing, and production environments.

What is Dockerfile?

A Dockerfile is a text file containing commands to build a Docker build image. It acts like a blueprint, specifying the environment, dependencies, and configurations of the application necessary to run in a container. The file does not have any name with an extension; it just has the word Dockerfile.

Structure and Usage

  • Syntax: Directives are each in the form DIRECTIVE argument (e.g., FROM ubuntu), which gets executed in a sequence during building.
  • Comments: Lines that start with # are for adding comments.
  • Best Practices: Write commands in uppercase for readability.

Dockerfiles build automatically create consistent, reusable, and portable Docker images. They streamline the deployment process, ensuring that applications run the same way in development, testing, and production environments.

Dockerfile Instructions:

InstructionExplanationExample
FROMSpecifies the base image to use.FROM ubuntu:20.04
RUNExecutes commands during the image build process.RUN apt-get update && apt-get install -y python3
ENVSets environment variables available during build and runtime.ENV APP_ENV=production
COPYCopies files or directories from the local system to the image.COPY app/ /app/
ADDSimilar to COPY, but also supports URLs and tar file extraction.ADD https://example.com/file.tar.gz /app/
EXPOSESpecifies the port the container will expose.EXPOSE 8080
WORKDIRSets the working directory for subsequent instructions.WORKDIR /app
VOLUMECreates or mounts a volume for the container.VOLUME /data
USERSets the user to run commands inside the container.USER nonroot
LABELAdds metadata to the image, such as version or maintainer information.LABEL version="1.0"
ARGDefines build-time variables that don’t persist in the container.ARG BUILD_VERSION=1.0
SHELLCustomizes the shell used for RUN, CMD, and ENTRYPOINT.SHELL ["/bin/bash", "-c"]
CMDSpecifies the default command to run in a container. Can be overridden.CMD ["python3", "app.py"]
ENTRYPOINTDefines the main process for the container, allowing it to behave like an executable.ENTRYPOINT ["python3", "app.py"]

How to build a Docker image from Dockerfile: Step-by-step

Building a Docker image from a Dockerfile is a relatively simple process. To get started with it, here are the steps you need to follow:

Install Docker

Before proceeding, first, ensure Docker is installed in your system. You can download and install Docker from the official Docker website. For Linux, you can make use of a package manager like apt or yum. For Windows and Mac, a Docker Desktop is required.

Create a Project Directory

Set up a project-specific directory. This directory will contain your Dockerfile and other relevant files that might be needed when building the Docker image. It can be made using a terminal or file explorer.

mkdir my_project && cd my_project

Select a Base Image

Identify an appropriate base image for your application from a container registry such as Docker Hub. For instance, you may select a Python-based image if you are working with a Python application or a Node. Js-based image for your JavaScript app. You indicate your base image using the FROM instruction in your Dockerfile.

FROM python:3.9-slim

Create a Dockerfiles

Create a plain text file named Dockerfile in your project directory. Add instructions to this file defining the steps for building your image: installing dependencies, copying application files, and setting up runtime commands, among others.

Example:

FROM python:3.9-slim
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD ["python", "app.py"]

Build a Docker Image

You create the Docker image using the docker build command with your Dockerfile. The -t flag enables you to tag your image with a name and optionally a version. Run this from the directory that contains the Dockerfile build. 

Docker build -t my_app_image

Once the build is done, you can confirm that your image has been successfully created by running docker images. Now, you should test your image by using the command docker run to run a container based on your newly built image.

What is a Docker Image?

A Docker image is an ultra-lightweight, standalone, and executable software package that contains everything needed to run an application. This includes the application code, runtime environment, system tools, libraries, and settings. Docker images form the basis from which to generate Docker containers. Docker containers are essentially the runtime instances of these images.

Images are formed by a defined set of instructions in a Dockerfile. There is one instruction corresponding to a single layer in a Docker image with layers stacked onto each other to fully form the resulting image. Beyond simplifying this building process, this layer-based system enhances an image's potential for reuse and efficiency as well.

Test the Docker Image

To run a Docker image, you would use the docker run command. This is how you do it:

$ docker run -p 80:3000 yourusername/example-node-app

Here's what's going on in this command:

-p is used to map the ports between your host machine and the container. In this example, port 80 on your host will be mapped to port 3000 inside the app, which lives in the container. Now you can access your app by going to https://localhost in your browser.

Use the -d argument to run the container in detached mode:

$ docker run -d -p 80:3000 yourusername/example-node-app

Pushing a Docker image to the Docker repository

To make your Docker image available for use on other machines, you'll need to push it to a Docker registry. One popular choice is Docker Hub, where Docker images are stored. First, create an account on Docker Hub if you haven't already.

Once your Docker Hub account is set up, log in using your credentials:

$ docker login

Enter your Docker Hub username and password to authenticate.

Now, let's tag our image with a version number, so we keep track of any changes:

$ docker tag yourusername/example-node-app 
yourdockerhubusername/example-node-app:v1

We can now push the tagged image to Docker Hub:

$ docker push yourusername/example-node-app:v1

After pushing our image, we can access it from anywhere in the world and easily deploy it across different environments.

If you're interested in monitoring your containers, you can use various Docker commands to manage them. For instance, you can list running containers with:

$ docker ps

To inspect a specific container, use:

$ docker inspect <container_id>

To view logs for a container, run:

$ docker logs <container_id>

To stop a running container, execute:

$ docker stop <container_id>

Proper logging and monitoring are very important when deploying applications in production. Consider using tools like Retrace, which offers excellent support for Docker containers.

Conclusion

The Docker build command is one of the tools that developers use to package their applications into portable containers, which can be easily deployed across different environments. By now, you should have a good understanding of the Docker build command and how to use it to create customized Docker images to make your applications more portable.

Thank you for choosing Prioxis! We're dedicated to equipping developers with powerful cloud solutions that prioritize performance and reliability. At Prioxis, you can expect excellent support and a seamless experience as you navigate your development journey.