SoFunction
Updated on 2025-03-10

docker uses dockerfile to build images

dockerfile is a text file used to define and build a docker image. It consists of lines of instructions and parameters to describe the image construction and configuration process; it consists of basic images, software package installation, file copying, environment variable settings, etc.;

To build images based on dockerfile, you can use the docker build command, and use -f to specify the specific dockerfile file;

The steps to build an image using dockerfile are as follows: Write a dockerfile file --> docker build image --> docker run image;

Dockerfile overview

The Dockerfile file needs to be placed in a directory, which contains all the files that build the image. It is the context directory of this execution (which can be understood as the docker root directory), and can create a subdirectory.
In the Dockerfile file, the "#" sign starts with comments, and each behavior is "INSTRUCTION arguments", which is used to uppercase representing keywords (but not case sensitive), and lowercase represents values ​​afterwards.
The first line of each Dockerfile (except comment line), the "FROM" keyword must be used.
When building the image using docker build, the context directory we specified is packaged and passed to the docker engine. Not all files in this context directory will be used in Dockerfile. Too large directories sent to the docker engine will affect the construction speed. You can define the .dockerignore file in this directory, write the file name of the unused file to block the .dockerignore file, and support wildcard characters.
Minimize the number of layers of the mirror. Each line of command in the Dockerfile is one layer. Too many layers affect the construction efficiency.
The commands in the Dockerfile file are executed line by line from top to bottom.

Directives and parameters for DockerFile image

A Dockerfile is a text file that contains a series of instructions and parameters for building a Docker image. Here are the common structures and components of Dockerfile:

instruction illustrate
FROM Specify the basic image and start building a new image
RUN Execute the command and create a new mirror layer
CMD Provides default commands executed when container starts
ENTRYPOINT Set the entry point when the container is started
COPY Copy new file or directory from build context into mirror
ADD Similar to COPY, but can decompress archive files and add execution permissions
ENV Set environment variables
ARG Define variables used at build time
VOLUME Define a mount point for data persistence or sharing
EXPOSE Declare the port to listen when the container is running
WORKDIR Set up the working directory
USER Specify the user to run the command
HEALTHCHECK Health check commands that define containers
ONBUILD Specifies the commands executed when the created image is used as the base image of other images
STOPSIGNAL Configure the signal to stop the container
LABEL Add metadata to the mirror
SHELL Specifies the shell used to execute RUN, CMD, ENTRYPOINT, and SCRIPT instructions
MAINTAINER Specify the maintainer's name and an optional email address (deprecated)

DockerFile image case

# Use basic images, which is the starting point for building a new imageFROM ubuntu:20.04 AS base

# Maintainer information (using LABEL instead of MAINTAINER)LABEL maintainer="Name <email>"

# Set environment variables, which will affect subsequent RUN instructions and the environment when the container is runningENV MY_ENV_VAR="my_value"
ENV PATH="/usr/local/bin:${PATH}"

# The RUN directive executes the command and creates a new mirror layer for installing the software packageRUN apt-get update && apt-get install -y \
    curl \
    git \
    vim

# Working Directory: WORKDIR Set the working directory, and subsequent RUN, CMD, and ENTRYPOINT instructions will be based on this working directoryWORKDIR /app

# Copy the current directory contents to the /app directory in the container, and copy the new file or directory into the image from the build context (usually the directory where the Dockerfile is located).COPY . /app

# Add extra files to the image: ADD is similar to COPY, but can handle tar compressed files and can perform some special operationsADD ./files/* /app/files/

# Define a mount point: VOLUME Define a mount point for data persistence or data sharing between containersVOLUME /var/log/myapp

# EXPOSE Declares the port to listen for when the container runsEXPOSE 8000

# Specify the commands executed when container starts: The CMD directive provides the default commands executed when container starts, which can be overridden by the parameters of docker runCMD ["python", "/app/"]

# Build phase: Compile the application and use multi-stage construction to reduce the size of the final imageFROM base AS builder
RUN apt-get update && apt-get install -y build-essential
COPY --from=base /app /app
RUN make /app

# Production stage: Run the application, use basic mirrors as the running environment for building the productFROM base AS production
COPY --from=builder /app/bin /app/bin
CMD ["/app/bin/myapp"]

# Health Check: HEALTHCHECK Defines the health check command of the container to improve the reliability of the containerHEALTHCHECK --interval=30s --timeout=30s --retries=3 \
  CMD curl -f http://localhost:8000 || exit 1

# User: USER Specifies the user and user group to run the command to improve securityUSER 1000:1000

# Build cache: ARG defines variables for building cache, which can be used for parameter passing during the build processARG BUILD_DATE
LABEL -date=$BUILD_DATE

# Stop signal: STOPSIGNAL The signal configured to stop the container can be any POSIX stop signal or digitalSTOPSIGNAL SIGTERM

# Use SHELL directive: SHELL specifies the shell used to execute the instructions, which can be bash, sh, etc.SHELL ["/bin/bash", "-c"]

explain

Basic mirror: useubuntu:20.04As a basic image.

Maintainer information: useLABELReplace the abandonedMAINTAINER

Environment variables: Set environment variablesMY_ENV_VARand updatesPATH

Update and install software: useRUNInstall the package.

Work Directory: Set the working directory to/app

Copy the file: useCOPYandADDAdd the file to the image.

Mounting point: Define a mount point.

Exposed ports: Declare the port to listen for when the container runs.

Default command: Sets the default commands executed when the container starts.

Construction phase: usebuilderstage compilation of the application.

Production stage: useproductionRun the application in stages.

Health check: Defines the health check command for the container.

user: Specify the user to run the command.

Build cache: useARGDefines the variables at build time.

Stop signal: Configure the signal to stop the container.

SHELL: Specifies the shell used to execute the instructions.

Command details

Basic mirroring instructions (FROM)

FROM ubuntu:20.04

FROMThe directive specifies the basic image, which is the basis for building a new image.

Maintenance command (MAINTAINER) (Optional, deprecated, it is recommended to use LABEL)

LABEL maintainer="name <email>"

LABELUsed to add metadata, replacing the previous oneMAINTAINERinstruction.

Environment variable directive (ENV)

ENV PATH /usr/local/bin:$PATH

 ENVUsed to set environment variables.

Working directory instructions (WORKDIR)

WORKDIR /app

 WORKDIRSets the current working directory in the container.

Copy command (COPYandADD)

COPY . /app

COPYCopy new files or directories from the build context to the file system of the container.

ADDandCOPYSimilar, but with additional functionality when handling archive files.

 Run commands (RUN)

RUN apt-get update && apt-get install -y nginx

 RUNDirectives are used to execute commands and save their results (such as installed software) as new mirroring layers.

Expose command (EXPOSE)

EXPOSE 80

EXPOSEDirective notifies the port that the Docker daemon container listens when it runs.

Start command (CMD)

CMD ["nginx", "-g", "daemon off;"]

CMDThe directive specifies the default commands executed when the container starts.

Health Check Instructions (HEALTHCHECK)

HEALTHCHECK --interval=30s --timeout=30s --retries=3 CMD curl -f http://localhost || exit 1

HEALTHCHECKDirectives are used to specify how to check container health.

Build cache directive (ARG)

ARG VERSION=latest

ARGDirectives are used to define variables during the build process.

Multi-stage construction (FROMUsed multiple times in Dockerfile)

# Phase 1: Construction PhaseFROM golang:1.16 AS builder
WORKDIR /app
COPY go.* ./
RUN go mod download
COPY . .
RUN go build -o /my-go-app

# Phase 2: Production EnvironmentFROM alpine:latest
RUN apk add --no-cache ca-certificates
WORKDIR /root
COPY --from=builder /my-go-app .
CMD ["./my-go-app"]

Using multi-stage builds can reduce the size of the final image, copying the build product from the build phase to the production environment image.

DockerFile Practical Case 1: Spring Boot Application

Project structure

Suppose our Spring Boot application structure is as follows:

springbootapp/
├── src/
│   ├── main/
│   │   ├── java/com/
│   │   │   └── example/
│   │   │       ├── controller/
│   │   │       │   └── 
│   │   │       └── 
│   │   └── resources/
│   │       └── 
├── 
└── Dockerfile

It is a Spring Boot controller.

It is the main program of Spring Boot application.

Contains application configuration.

It is the Maven build configuration file.

Dockerfile

# Use official Java basic image with Maven environment for building projectsFROM maven:3.8.1-jdk-11 AS build
# Set up the working directoryWORKDIR /app
# Copy the project file into the containerCOPY src ./src
COPY  .
# Build a project using MavenRUN mvn -f  clean package

# Use official Java basic image to run applicationsFROM openjdk:11-jre-slim
# Set up the working directoryWORKDIR /app
# Copy the built jar file from the build stage to the run stageCOPY --from=build /app/target/*.jar ./
# Expose portsEXPOSE 8080
# Run Spring Boot appCMD ["java", "-jar", ""]

Build and run Docker images

Build a mirror

docker build -t springbootapp .

Run the container:

docker run -p 8080:8080 springbootapp

DockerFile Practical Case 2: Spring Boot and MyBatis Multi-Module Project

Project structure

The multi-module Spring Boot and MyBatis application structure is as follows:

multimoduleapp/
├── 
├── Dockerfile
└── app/
    ├── common/
    │   ├── 
    │   └── src/
    │       ├── main/
    │       └── java/
    │           └── com/
    │               └── example/
    │                   └── common/
    │                       └── 
    ├── api/
    │   ├── 
    │   └── src/
    │       ├── main/
    │       │   ├── java/
    │       │   │   └── com/
    │       │   │       └── example/
    │       │   │           └── api/
    │       │   │               └── 
    │       │   └── resources/
    │       └── 
    └── service/
        ├── 
        ├── src/
        │   ├── main/
        │   │   ├── java/
        │   │   │   └── com/
        │   │   │       └── example/
        │   │   │           └── service/
        │   │   │               └── 
        │   │   └── resources/
        └── src/
            └── main/
                └── resources/
                    └── mapper/
                        └── 

It is a universal service.

It is a Spring Boot controller.

It is a business logic service.

is a MyBatis mapping file.

It is the Maven build configuration file.

Dockerfile

# Use official Java basic image with Maven environment for building projectsFROM maven:3.8.1-jdk-11 AS build
# Set up the working directoryWORKDIR /app
# Copy the project file into the containerCOPY . .
# Build a project using MavenRUN mvn -f  clean package

# Use official Java basic image to run applicationsFROM openjdk:11-jre-slim
# Set up the working directoryWORKDIR /app
# Copy the built jar file from the build stage to the run stageCOPY --from=build /app/api/target/*.jar ./
# Expose portsEXPOSE 8080
# Run Spring Boot appCMD ["java", "-jar", ""]

Build and run Docker images

Build a mirror

docker build -t multimoduleapp .

Run the container:

docker run -p 8080:8080 multimoduleapp

Summarize

This is the end of this article about docker using dockerfile to build images. For more related content on dockerfile building docker images, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!