[Docker] First introduction to Docker, use of basic Docker commands, creation of Dockerfile custom image


Preface: Challenges of Project Deployment

When deploying large projects, you often face multiple components, complex dependencies, and differences between different environments. These factors can lead to the following problems:

  1. Complex dependencies: Due to the large number of project components, the dependencies between each component become complex, and version mismatches or compatibility issues are prone to occur.

  2. Compatibility issues: Projects may encounter compatibility challenges in different environments, causing components that work fine in one environment to have issues in another.

  3. Environment differences: There are differences between development, testing and production environments, which may involve inconsistencies in operating systems, library versions, configurations, etc., increasing the complexity of deployment.

These challenges make project deployment complex and error-prone. In order to solve these problems, the introduction of Docker technology is an effective solution. Docker's containerization feature can provide a consistent operating environment, simplify dependency management, and alleviate differences between different environments, thereby improving the reliability and efficiency of deployment. In the following content, we will take a deeper look at the basic concepts of Docker and how to use Docker to solve these project deployment challenges.

1. First introduction to Docker

1.1 What is Docker

Docker is an open source containerization platform designed to 简化应用程序的开发、交付和部署过程. By using container technology, Docker is able to 应用程序、所有依赖项以及程序运行所需要的环境package things into a standalone container. This container contains everything needed to run the application, including the operating system, libraries, code, and more. This packaging method allows applications to run in a consistent manner in any environment, thereby achieving the advantages of cross-platform, portability and rapid deployment.

Docker is a technology designed to deliver applications quickly and run them efficiently. It provides the following main features:

  1. Containerized packaging: Docker allows the program, its dependencies, and the running environment to be packaged into an independent image. This image contains everything the application needs, from the operating system to all dependent libraries, forming a portable and consistent running environment.

  2. Cross-platform portability: Because the Docker image is an independent, lightweight package, it can be easily migrated to any Linux operating system that supports Docker without worrying about environment differences.

  3. Sandbox isolation: When running, Docker uses the sandbox mechanism to create an independent running environment for each container, so that various applications do not interfere with each other within the container. This isolation ensures security and reliability.

  4. Convenient management commands: Docker provides a simple and powerful command line tool. Users can use one line of commands to complete operations such as starting, stopping, and removing containers. This convenience makes application development, testing, and deployment more efficient.

Overall, Docker provides developers with an advanced, portable containerization solution that enables rapid deployment and the convenience of cross-platform operation by packaging applications and their runtime environments into images. At the same time, the sandbox isolation mechanism ensures the independence between multiple applications, making Docker an ideal choice for modern application development and deployment.

1.2 The difference between Docker and virtual machines

Docker and virtual machines are two common containerization technologies. They have some differences in the way they implement virtualization and isolation, and in their performance. Before understanding Docker and virtual machines, first we can briefly understand their hierarchical structure:

Docker vs virtual machine

From the above figure, we can see that the virtual machine uses the hypervisor to simulate the computer hardware on the operating system, and then installs the operating system on the virtual hardware; while the Docker container runs directly on the operating system. Therefore, the performance of Docker will be far better than that of virtual machines.

Let's compare the features of Docker and virtual machines:

characteristic Docker virtual machine
performance Close to native Poor performance
Hard drive usage Usually MB Generally GB
start up Second level Minute level

Advantages of Docker:

  1. Performance: Docker containers run directly on the kernel of the host operating system, so the performance is close to native, while virtual machines need to run under the management of a hypervisor, and their performance is relatively poor.

  2. Hard disk usage: Docker images are lightweight, usually only in the MB level, while virtual machine images are often in the GB level, so Docker is more efficient in hard disk usage.

  3. Startup speed: Docker containers start very quickly and can reach the start time of seconds, while the startup of virtual machines takes a longer time, usually minutes.

Generally speaking, Docker is suitable for rapid deployment and lightweight applications, while virtual machines are more suitable for complex applications that require complete isolation. The choice of which technology to use depends on the specific application scenario and requirements.

1.3 Images, containers and image hosting platforms

In the world of Docker, images and containers are two core concepts, and understanding them is the key to using Docker.

What is a mirror?

An image is a lightweight, self-contained executable package that contains everything needed to run an application: code, runtime, system tools, system libraries, and settings. Simply put, an image is a packaging of an application.

Components:

  1. Application Code: All files and code for your application.
  2. Runtime: Configuration file that defines how the application runs.
  3. System tools: Tools for the operating system and applications.
  4. System libraries: Any library files required by the application.

Features:

  • Immutability: Once built, the contents of the image cannot be changed.
  • Lightweight: An image is typically small because it contains only the minimum content required to run the application.

example:

  • An image running a Node.js application may contain the Node.js runtime, application code, and some operating system tools.

What is a container?

A container is a running instance of an image. A container can be thought of as a lightweight, independent executable package that contains applications, runtimes and system tools and executes according to the definition of the image.

Features:

  • Isolation: Containers are isolated from each other, and changes in one container will not affect other containers.
  • Portability: Containers can run in any environment that supports Docker.

example:

  • Use a Node.js image to run two identical applications, each running in a separate container, isolated from each other.

Mirror hosting platform:

DockerHub:

  • DockerHub is a Docker image hosting platform, similar to cloud storage, where we can also store and share our own images.

Other image hosting platforms:

  • In addition to DockerHub, there are also some similar services in China, such as NetEase Cloud Image Service, Alibaba Cloud Image Library, etc. They provide faster and more stable image download services and support the storage of users' private images. In addition, we can also create our own private image hosting platform.

Schematic diagram:
Mirror hosting platform

In short, understanding the relationship between images and containers and their role in Docker is the basis for using Docker for application development and deployment. Docker's success is due in part to this lightweight, portable containerization technology that makes it easier and more efficient to build, distribute, and run applications.

1.4 Docker architecture analysis

Docker's architecture design is simple and flexible, and is divided into two parts: client and server. They work together to create, run and manage containers.

Client

The client is the interface for users to interact with Docker. Users can communicate with the server through the command line, graphical interface, or use the API provided by Docker to send instructions to manage Docker.

Server

The server is the daemon process of Docker, responsible for processing instructions from the client and managing various tasks of Docker. The main components of the server include:

  1. Docker Daemon: A daemon process that runs on the host and is responsible for managing the creation, running, and stopping of containers. It is also responsible for communicating with other Docker daemons, as well as communicating with clients.

  2. Docker REST API: Communication between client and daemon occurs through REST API. The client can interact with Docker by sending commands to the daemon through the REST API.

  3. Docker Registry: A service used to store Docker images. Docker officially provides Docker Hub as the default public registry, and users can also use private registries or other public registries to store and share images.

Architecture diagram

Docker architecture

In this architecture, the client and server can run on the same host or be connected on different hosts through the network. When clients send Docker commands, they communicate with the server through the REST API, and the server performs corresponding operations according to the instructions.

Interaction process

  1. Client sends commands: Users send Docker commands through the command line or other tools, such as creating images, running containers, etc.

  2. Commands are sent to the server: The client sends commands to the server and communicates through the REST API.

  3. Server execution command: After receiving the command, Docker Daemon performs corresponding operations, such as creating or managing containers, pulling or pushing images, etc.

  4. The results are returned to the client: After the server executes the command, it returns the results to the client, and the user can see the execution results.

Docker's CS (Client-Server) architecture allows users to interact with Docker through simple commands, while the server is responsible for specific management and operations, making the entire system more modular and easy to expand.

1.5 Docker installation in CentOS

Docker is a powerful containerization platform. In order to use Docker on CentOS, we will follow the following steps to install it.

  1. Uninstall old version (optional)

If you have installed an older version of Docker before, you can uninstall it with the following command:

sudo yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-selinux \
                  docker-engine-selinux \
                  docker-engine \
                  docker-ce
  1. Install dependent tools

Install necessary tools and dependencies:

sudo yum install -y yum-utils device-mapper-persistent-data lvm2
  1. Add Docker repository

Add Docker's official repository. Here we use Alibaba Cloud’s image acceleration address:

sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
  1. Install Docker engine

Install the latest version of Docker engine:

sudo yum install docker-ce docker-ce-cli containerd.io
  1. Start the Docker engine

Start the Docker engine and set it to start at boot:

sudo systemctl start docker
sudo systemctl enable docker
  1. Verify installation

Run the following command to verify that Docker is installed correctly:

docker --version
docker info
  1. Configure image acceleration

In order to improve the download speed of Docker images, configure the image accelerator. Taking Alibaba Cloud as an example, go to Alibaba Cloud Container Image Service to register an account and obtain the acceleration address. Then /etc/docker/daemon.jsonadd the following in:

{
    
    
  "registry-mirrors": ["https://your-registry-mirror"]
}

Replace https://your-registry-mirrorwith your acceleration address.

After completing the above steps, Docker is successfully installed and configured on our CentOS system. Now, you can docker run hello-worldtest whether Docker is working properly by running.

2. Basic operations of Docker

Docker's operations are mainly divided into three aspects: image operations, container operations and data volume management. The relevant commands in these three aspects are introduced in detail below.

2.1 Operating Docker image commands

In the world of Docker, an image is the packaging and distribution unit of an application. Understanding and skillfully using image-related commands is the key to using Docker. This article will introduce some common mirror operation commands in detail.

2.1.1 Commands related to mirroring operations

Image name resolution

In Docker, image names usually consist of two parts: [repository]:[tag]. If not specified tag, it will be used by default latest, indicating the latest version of the image. For example, mysqlthe image name:

Overview of mirroring operation commands

As can be seen from the above figure, the mirroring commands mainly include the following types:

  1. docker pull: Pull the image from the remote warehouse.

    docker pull image_name
    
  2. docker push: Push the local image to the remote warehouse.

    docker push image_name
    
  3. docker build: Build the image based on the Dockerfile.

    docker build -t image_name .
    
  4. docker save: Save the image as a tar compressed package.

    docker save -o image_name.tar image_name
    
  5. docker load: Load an image from a tar archive.

    docker load -i image_name.tar
    

2.1.2 Example 1: Pull an nginx image from DockerHub

DockerHub is Docker's official image repository, providing a large number of official and community-maintained images. The following is an example of pulling the nginx image from DockerHub:

docker pull nginx

The above command will download the latest version of nginx image from DockerHub to local. Then use docker imagesthe command to view the currently existing images:

If you need a specific version of the image, you can use:

docker pull nginx:version

Just replace versionit with the specific version you need.

2.1.3 Example 2: Use save to export the nginx image to disk, and then load it back through load

First, regarding the syntax of saveand load, we can use --helpthe option to view:

saveOrder:

docker save --help

It can be found that savethe function of the command is to save the image as a tarcompressed package in a format, use -othe option to represent STDOUTstandard output, and write it to a file.

For example, save the above nginximage to disk:

docker save -o nginx.tar nginx:latest

loadOrder:

docker load --help


It can be found that loadthe function of the command is to tarload a formatted compressed package into a Docker image, use -ithe option to represent STDINthe standard input, and write it to the specified file. -qThe option will not output the log to the terminal.

For example, load nginx.tarthe compressed package just now:

First delete nginx:latestthe image:

Then load nginx.tarthe compressed package:

2.2 Detailed explanation of Docker container commands

A container is a running instance of Docker and the specific execution environment of the image. Understanding and being proficient in using container-related commands is a core part of using Docker. Next, we will introduce some common container operation commands in detail.

2.2.1 Commands related to operating containers

The container operation command is shown in the figure below:

Docker container operation commands

Let’s understand these commands one by one:

  1. docker run: Run the container.

    docker run options image_name
    
  2. docker pause: Pause the container.

    docker pause container_id
    

    This command can pause a running container and suspend its process.

  3. docker unpause: Restore container.

    docker unpause container_id
    

    Correspondingly docker pause, this command is used to resume a suspended container.

  4. docker stop: Stop the container.

    docker stop container_id
    

    With this command, you can stop a running container, but the container instance still exists.

  5. docker start: Start a stopped container.

    docker start container_id
    

    Using this command, you can start a previously stopped container.

  6. docker rm: Remove the container.

    docker rm container_id
    

    With this command, you can delete a stopped container instance. Please note that deleting the container does not delete the image.

  7. docker exec: Execute commands in a running container.

    docker exec options container_id command
    

    This command is used to execute specific commands in a running container, for example:

    docker exec -it container_id /bin/bash
    

    The above command will open an interactive bash shell in the container.

  8. docker logs: View container logs.

    docker logs container_id
    

    This command is used to view the output log of the container.

  9. docker ps: List running containers.

    docker ps options
    

    With this command, you can list running containers. Use -athe option to list all containers, including stopped ones.

These commands cover the core aspects of Docker container operations, and through them, you can easily manage and use Docker containers. In practice, by cleverly combining these commands according to specific needs, containers can be run and managed more efficiently.

Supplement: Explanation of the difference between pause pauseand stop stop:

docker pauseand docker stopare two different commands, their functions are to pause the container and stop the container respectively. The differences between them are explained below:

docker pause

  • Function: Pause all processes of the container and freeze the state of the container.
  • Usage scenario: You can use this command when you want to retain the current state of the container but temporarily stop all processes in the container. When a container is in a suspended state, its file system and data in memory still exist, but all processes within the container will be suspended and will no longer execute.
  • example:
    docker pause container_id
    

docker stop

  • Function: Stop the running of the container and terminate all processes of the container.
  • Usage scenario: When you want to completely terminate the running of the container, including stopping all processes in the container and releasing the occupied resources, you can use this command. When the container is stopped, you can choose to delete the container or restart it.
  • example:
    docker stop container_id
    

Summary of differences:

  • docker pausePause the container, freeze the container state, and retain the data in the container.
  • docker stopStop the container, terminate all processes in the container, and retain the data in the container.

When choosing to use these two commands, you need to decide based on specific needs. If you need to temporarily stop all processes in the container while retaining the container state, you can use it docker pause; if you want to completely stop the running of the container and release resources, you can use it docker stop.

2.2.2 Example 1: Running nginx image

You can run an image in a new container with the following command nginx. For example:

docker run -d -p 8080:80 --name my-nginx nginx:latest

illustrate:

  • -dOptions: Let the container run in the background;
  • -pOption: Map the host's port 8080 to the container's port 80, that is, access the host's port 8080 to access the container's port 80;
  • --nameOption: Specify the name of the container, which needs to be unique;

    when the operation is successful, the unique ID of the container will be output in the terminal.

You can use docker psthe command to view the currently running containers:

In addition, in order to verify that the container is successfully started and running, you can access it nginxin a browser using :宿主机IP:8080


At this time, the welcome page appears nginx, indicating that the container has been successfully started and run.

2.2.3 Example 2: Inside the Nginx container, modify the content of the HTML file

  1. First, we can docker execget into the contents of the container using the command:
docker exec -it my-nginx bash

illustrate:

  • -itCreate a standard input and output terminal for the currently entered container, allowing us to interact with the container;
  • my-nginx: The name of the container to enter;
  • bash: linuxCommand to enable terminal interaction.


The hostname at this time becomes the partial ID of the container.

  1. Then enter nginxthe HTMLdirectory where the file is located /usr/share/nginx/html:

  2. Modify index.htmlthe contents of the file:

If we want to use to vimmake modifications, we find that the Docker container does not provide viman editor. In addition, we can also find that the Docker container actually only provides a small number of commands. The reason is to keep the container lightweight.

At this point, we can use sedthe command to make modifications:

# sed
sed -i 's#Welcome to nginx#Docker 非常简单!#g' index.html
sed -i 's#<head>#<head><meta charset="utf-8">#g' index.html # 修改编码方式为 UTF-8

  1. Visit it in the browser again:

2.3 Detailed explanation of commands to operate Docker data volumes

2.3.1 The problem of coupling between containers and data

In containerized applications, the coupling between the container and its data may cause some problems:

  1. Inconvenient to modify: When you need to modify the data inside the container, you must enter the container to make modifications, which is not convenient enough.
  2. Data is not reusable: modifications to the data in the container are not visible to the outside, and newly created containers cannot reuse these modifications.
  3. Difficulty in upgrading and maintaining: If the data is in a container, upgrading the container means deleting the old container, and all data will be deleted.

To solve these problems, Docker's data volumes can be used.

2.3.2 What is a data volume?

A volume is a directory that can be shared and reused between containers. It exists on the host rather than within the container. Through the data volume, a directory in the host file system is mapped to a directory in the container to achieve data sharing and persistence.

As shown below:
data volume

It can be found that the data volume actually helps establish a mapping relationship between the files in the host file system and the files in the Docker container.

2.3.3 Data volume related operation commands

Docker provides a series of commands to manage data volumes. The basic syntax is as follows:

docker volume [COMMAND]

Among them, COMMANDit can be one of the following operations:

  • create: Create a data volume.
  • inspect: Displays information about one or more data volumes.
  • ls: List all data volumes.
  • prune: Delete unused data volumes.
  • rm: Delete one or more specified data volumes.

Some of the commonly used commands are described in detail below.

  1. Create data volume

To create a data volume, use docker volume createthe command:

docker volume create my_volume

The above command will create a my_volumedata volume named .

  1. View data volume information

Use docker volume inspectthe command to view detailed information about one or more data volumes:

docker volume inspect my_volume
  1. List all data volumes

Use docker volume lsthe command to list all data volumes:

docker volume ls
  1. Delete data volume

To delete one or more specified data volumes, use docker volume rmthe command:

docker volume rm my_volume
  1. Clean up unused data volumes

Use docker volume prunethe command to delete unused data volumes:

docker volume prune

The above command will prompt you whether to delete unused data volumes. After confirmation, the deletion operation will be performed.

Through the management commands of these data volumes, the data in the container can be processed more flexibly, and data persistence and sharing can be achieved. In practical applications, data volumes are a very useful feature, especially for application scenarios that require persistent storage.

2.3.4 Example 1: Create a data volume and check the directory location of the data volume on the host

  1. Create data volume
docker volume create html


2. View all current data volumes

docker volume ls

  1. View htmldetails of a data volume
docker volume inspect html

It can be found that htmlthe mount point in the host is: /var/lib/docker/volumes/html/_data.

2.3.5 Example 2: Create a data volume while creating an nginx container, and modify the HTML content through the data volume

When we create a container, we can use -vparameters to mount a data volume to a container directory:

docker run \
  --name my-nginx \
  -v html:/usr/share/nginx/html \
  -p 8080:80 \
  -d \
  nginx:latest

  1. Enter htmlthe location of the data volume

  2. and modify index.htmlthe content

  3. Access via browser nginx

    At this point, the files of the Docker container content have been successfully modified through the data volume.

3. Creation of Dockerfile custom image

3.1 Detailed explanation of the structure of image files

A Docker image is a lightweight, executable software package that contains an application and the components it needs to run. Its file structure is layered, with each layer containing some changes to the file system. Let’s take a closer look at the structure of an image file.

  1. Mirror hierarchy

The image hierarchy consists of multiple layers, as shown in the figure below:

Mirror hierarchy

These levels are divided into the following categories:

  1. Base Image layer: Contains basic system function libraries, environment variables and file systems. This layer forms the basis of the image.

  2. Entrypoint layer: Contains the startup commands for the application. It defines the entry point for the application in the image.

  3. Other layers: Add application dependencies, installers, etc. on the basis of Base Image to complete the installation and configuration of the entire application. Each layer is based on modifications of the previous layer.

  1. Layering advantages of mirroring

The layered design of Docker images has some advantages:

  • Efficient storage utilization: If multiple images share the same base layer, this layer only needs to be stored once, reducing storage space usage.

  • Fast distribution: The layered structure of the image also allows only the changed layer to be transferred, rather than the entire image, so it can be distributed and deployed faster.

Through such a layered structure, Docker achieves efficient management, storage and transmission of images, making the construction and distribution of containers more lightweight and faster.

3.2 Detailed explanation of Dockerfile file

  1. What is a Dockerfile

Dockerfile is a script file used to build images in Docker. It contains a series of instructions. Each instruction will be modified at the current level to form a new level, and finally combined into a complete container image.

  1. Dockerfile instructions

The following are some commonly used Dockerfile instructions and their descriptions:

instruction illustrate Example
FROM Specify the base image, and subsequent instructions will be built based on this image. FROM centos:7
ENV Set environment variables that can be used in subsequent instructions. ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk
COPY Copies files from the build context to the specified path in the image. COPY ./app.jar /usr/app/
RUN Execute Linux shell commands, generally used for operations such as installing software packages. RUN yum install -y gcc
EXPOSE Specify the port that the container listens on when running, which is visible to image users. EXPOSE 8080
ENTRYPOINT Specify the startup command applied in the container. This command will be called when the container is running. ENTRYPOINT ["java", "-jar", "app.jar"]

For more Dockerfile instructions and syntax details, please refer to the official documentation: Dockerfile reference

  1. Dockerfile

When building a Docker image, Docker will build the image layer by layer according to the instructions in the Dockerfile. Each instruction modifies the current level to form a new level.

For example, a simple Dockerfile is as follows:

# 使用基础镜像
FROM ubuntu:latest

# 执行一些命令
RUN apt-get update && apt-get install -y \
    nginx \
    && rm -rf /var/lib/apt/lists/*

# 设置工作目录
WORKDIR /app

# 复制文件
COPY . .

# 设置入口命令
CMD ["nginx", "-g", "daemon off;"]

In this example, each instruction will be modified based on the previous instruction to build a complete image that includes the base image, Nginx installation, working directory and entry command settings.

  1. Build images using Dockerfile

When building a Docker image, use the Dockerfile with the following command:

docker build -t my-image:tag path/to/Dockerfile-context
  • -t: Specify the name and label of the image.
  • path/to/Dockerfile-context: The context path where the Dockerfile is located.

For example, run the following command in a directory containing a Dockerfile:

docker build -t my-app:1.0 .

The above command will find the Dockerfile file in the current directory and build an image named my-appand labeled .1.0

3.3 Example 1: Build a new image based on the Ubuntu image and run a Java project

  1. Preparation
  • Step 1: Create a new empty folderdocker-demo

Step 1

  • Step 2: Copy Java project files

Copy the prepared Java jar package docker-demo.jarfile to docker-demothis directory

Step 2

  • Step 3: Copy JDK files

Copy the files prepared in advance jdk8.tar.gzto docker-demothis directory

Step 3

  1. Write Dockerfile

In docker-demothis directory, write a Dockerfilefile with the following content:

# 指定基础镜像
FROM ubuntu:16.04

# 配置环境变量,JDK的安装目录
ENV JAVA_DIR=/usr/local

# 拷贝 JDK 和 Java 项目的包
COPY ./jdk8.tar.gz $JAVA_DIR/
COPY ./docker-demo.jar /tmp/app.jar

# 安装 JDK
RUN cd $JAVA_DIR \
 && tar -xf ./jdk8.tar.gz \
 && mv ./jdk1.8.0_144 ./java8

# 配置环境变量
ENV JAVA_HOME=$JAVA_DIR/java8
ENV PATH=$PATH:$JAVA_HOME/bin

# 暴露端口
EXPOSE 8090

# 入口,Java 项目的启动命令
ENTRYPOINT java -jar /tmp/app.jar
  1. Build and run Docker images

In docker-demothe directory, execute the following command to build the Docker image:

docker build -t java-app:1.0 .

Build Image

Run this image:

docker run -d -p 8090:8090 --name java-app java-app:1.0

Run Container

Finally visit in the browser: http://宿主机IP:8090/hello/count

Browser

Through this example, we successfully built an image containing a Java project based on the Ubuntu image and ran a container. This shows the use of Dockerfile and how to run a Java application in a container.

3.4 Example 2: Based on the java:8-alpine image, modify the Dockerfile of Example 1

In Example 1, we used Ubuntu as the base image. In this example, we will use java:8-alpineas the base image, which is a more lightweight image suitable for scenarios where the container size is reduced.

what isjava:8-alpine

java:8-alpineIt is a Docker image based on the Alpine Linux distribution, specifically used to run Java applications. Let’s break down what this tag means:

  • java: This indicates that this image is prepared for Java applications.
  • 8: This indicates the Java version, specifically Java 8.
  • alpine: This indicates that the base operating system is Alpine Linux. Alpine Linux is a lightweight Linux distribution known for its compactness and simplicity.

Alpine Linux pays more attention to simplicity and security than traditional Linux distributions. Its package management system uses , instead of using or apklike Ubuntu and CentOS . Due to its streamlined design, Alpine Linux provides a smaller image size, which is very important for containerized applications.aptyum

Therefore, java:8-alpineimages are a lightweight option that is ideal for running Java applications.

  1. Modify Dockerfile

In docker-demothe directory, modify Dockerfilethe file as follows:

# 指定基础镜像
FROM java:8-alpine

# 拷贝 Java 项目的包
COPY ./docker-demo.jar /tmp/app.jar

# 暴露端口
EXPOSE 8090

# 入口,Java 项目的启动命令
CMD ["java", "-jar", "/tmp/app.jar"]
  1. Rebuild and run the Docker image

In docker-demothe directory, execute the following command to rebuild the Docker image:

docker build -t java-app:2.0 .

Run this image:

docker run -d -p 8090:8090 --name java-app-alpine java-app:2.0

Finally visit in the browser: http://宿主机IP:8090/hello/count

Through this example, we successfully used java:8-alpineas the base image to achieve the same Java project operation. Such modifications not only improve the lightweight of the container, but also reduce the size of the image.

Guess you like

Origin blog.csdn.net/qq_61635026/article/details/133578103