When building Docker images with a Dockerfile, we define the environment, dependencies, and applications within the image. The steps to build a Docker image are as follows:
Step 1: Writing the Dockerfile
A Dockerfile is a text file containing a series of instructions that define how to build a Docker image. A basic Dockerfile typically includes the following sections:
-
Base Image: Use the
FROMinstruction to specify an existing image as the base. For example:dockerfileFROM ubuntu:18.04 -
Maintainer Information: Use the
MAINTAINERinstruction to add author or maintainer information (optional). For example:dockerfileMAINTAINER yourname <yourname@example.com> -
Environment Configuration: Use the
ENVinstruction to set environment variables. For example:dockerfileENV LANG C.UTF-8 -
Install Software: Use the
RUNinstruction to execute commands, such as installing packages. For example:dockerfileRUN apt-get update && apt-get install -y nginx -
Add Files: Use the
COPYorADDinstruction to copy local files into the image. For example:dockerfileCOPY . /app -
Working Directory: Use the
WORKDIRinstruction to specify the working directory. For example:dockerfileWORKDIR /app -
Expose Ports: Use the
EXPOSEinstruction to expose ports for the container runtime. For example:dockerfileEXPOSE 80 -
Run Commands: Use the
CMDorENTRYPOINTinstruction to specify the command to run when the container starts. For example:dockerfileCMD ["nginx", "-g", "daemon off;"]
Step 2: Building the Image
Execute the following command in the directory containing the Dockerfile to build the image:
bashdocker build -t mynginx .
-t mynginx: Specify the image name and tag..: Specify the build context path, which is the current directory.
Step 3: Running the Container
After building, you can run the container using the following command:
bashdocker run -d -p 80:80 mynginx
-d: Run the container in the background.-p 80:80: Map the container's port 80 to the host's port 80.
Example
Suppose you need to deploy a Python Flask application. Your Dockerfile might look like this:
dockerfile# Use the official Python image as the base image FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set working directory WORKDIR /code # Install dependencies COPY requirements.txt /code/ RUN pip install -r requirements.txt # Copy local code into the container COPY . /code/ # Specify the command to run when the container starts CMD ["flask", "run", "--host=0.0.0.0"]
This Dockerfile defines how to install a Flask application, copy the code, and run the application.