Article directory
- Preface: Challenges of Project Deployment
- 1. First introduction to Docker
- 2. Basic operations of Docker
-
- 2.1 Operating Docker image commands
- 2.2 Detailed explanation of Docker container commands
- 2.3 Detailed explanation of commands to operate Docker data volumes
-
- 2.3.1 The problem of coupling between containers and data
- 2.3.2 What is a data volume?
- 2.3.3 Data volume related operation commands
- 2.3.4 Example 1: Create a data volume and check the directory location of the data volume on the host
- 2.3.5 Example 2: Create a data volume while creating an nginx container, and modify the HTML content through the data volume
- 3. 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:
-
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.
-
Compatibility issues: Projects may encounter compatibility challenges in different environments, causing components that work fine in one environment to have issues in another.
-
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:
-
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.
-
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.
-
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.
-
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:
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:
-
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.
-
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.
-
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:
- Application Code: All files and code for your application.
- Runtime: Configuration file that defines how the application runs.
- System tools: Tools for the operating system and applications.
- 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:
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:
-
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.
-
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.
-
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
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
-
Client sends commands: Users send Docker commands through the command line or other tools, such as creating images, running containers, etc.
-
Commands are sent to the server: The client sends commands to the server and communicates through the REST API.
-
Server execution command: After receiving the command, Docker Daemon performs corresponding operations, such as creating or managing containers, pulling or pushing images, etc.
-
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.
- 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
- Install dependent tools
Install necessary tools and dependencies:
sudo yum install -y yum-utils device-mapper-persistent-data lvm2
- 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
- Install Docker engine
Install the latest version of Docker engine:
sudo yum install docker-ce docker-ce-cli containerd.io
- Start the Docker engine
Start the Docker engine and set it to start at boot:
sudo systemctl start docker
sudo systemctl enable docker
- Verify installation
Run the following command to verify that Docker is installed correctly:
docker --version
docker info
- 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.json
add the following in:
{
"registry-mirrors": ["https://your-registry-mirror"]
}
Replace https://your-registry-mirror
with your acceleration address.
After completing the above steps, Docker is successfully installed and configured on our CentOS system. Now, you can docker run hello-world
test 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, mysql
the image name:
Overview of mirroring operation commands
As can be seen from the above figure, the mirroring commands mainly include the following types:
-
docker pull
: Pull the image from the remote warehouse.docker pull image_name
-
docker push
: Push the local image to the remote warehouse.docker push image_name
-
docker build
: Build the image based on the Dockerfile.docker build -t image_name .
-
docker save
: Save the image as a tar compressed package.docker save -o image_name.tar image_name
-
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 images
the 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 version
it 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 save
and load
, we can use --help
the option to view:
save
Order:
docker save --help
It can be found that save
the function of the command is to save the image as a tar
compressed package in a format, use -o
the option to represent STDOUT
standard output, and write it to a file.
For example, save the above nginx
image to disk:
docker save -o nginx.tar nginx:latest
load
Order:
docker load --help
It can be found that load
the function of the command is to tar
load a formatted compressed package into a Docker image, use -i
the option to represent STDIN
the standard input, and write it to the specified file. -q
The option will not output the log to the terminal.
For example, load nginx.tar
the compressed package just now:
First delete nginx:latest
the image:
Then load nginx.tar
the 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:
Let’s understand these commands one by one:
-
docker run
: Run the container.docker run options image_name
-
docker pause
: Pause the container.docker pause container_id
This command can pause a running container and suspend its process.
-
docker unpause
: Restore container.docker unpause container_id
Correspondingly
docker pause
, this command is used to resume a suspended container. -
docker stop
: Stop the container.docker stop container_id
With this command, you can stop a running container, but the container instance still exists.
-
docker start
: Start a stopped container.docker start container_id
Using this command, you can start a previously stopped container.
-
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.
-
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.
-
docker logs
: View container logs.docker logs container_id
This command is used to view the output log of the container.
-
docker ps
: List running containers.docker ps options
With this command, you can list running containers. Use
-a
the 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
pause
and stopstop
:
docker pause
and docker stop
are 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 pause
Pause the container, freeze the container state, and retain the data in the container.docker stop
Stop 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:
-d
Options: Let the container run in the background;-p
Option: 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;--name
Option: 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 ps
the 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 nginx
in 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
- First, we can
docker exec
get into the contents of the container using the command:
docker exec -it my-nginx bash
illustrate:
-it
Create 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
:linux
Command to enable terminal interaction.
The hostname at this time becomes the partial ID of the container.
-
Then enter
nginx
theHTML
directory where the file is located/usr/share/nginx/html
:
-
Modify
index.html
the contents of the file:
If we want to use to vim
make modifications, we find that the Docker container does not provide vim
an 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 sed
the 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
- 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:
- 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.
- 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.
- 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:
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, COMMAND
it 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.
- Create data volume
To create a data volume, use docker volume create
the command:
docker volume create my_volume
The above command will create a my_volume
data volume named .
- View data volume information
Use docker volume inspect
the command to view detailed information about one or more data volumes:
docker volume inspect my_volume
- List all data volumes
Use docker volume ls
the command to list all data volumes:
docker volume ls
- Delete data volume
To delete one or more specified data volumes, use docker volume rm
the command:
docker volume rm my_volume
- Clean up unused data volumes
Use docker volume prune
the 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
- Create data volume
docker volume create html
2. View all current data volumes
docker volume ls
- View
html
details of a data volume
docker volume inspect html
It can be found that html
the 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 -v
parameters 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
-
Enter
html
the location of the data volume
-
and modify
index.html
the content
-
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.
- Mirror hierarchy
The image hierarchy consists of multiple layers, as shown in the figure below:
These levels are divided into the following categories:
-
Base Image layer: Contains basic system function libraries, environment variables and file systems. This layer forms the basis of the image.
-
Entrypoint layer: Contains the startup commands for the application. It defines the entry point for the application in the image.
-
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.
- 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
- 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.
- 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
- 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.
- 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-app
and labeled .1.0
3.3 Example 1: Build a new image based on the Ubuntu image and run a Java project
- Preparation
- Step 1: Create a new empty folder
docker-demo
- Step 2: Copy Java project files
Copy the prepared Java jar package docker-demo.jar
file to docker-demo
this directory
- Step 3: Copy JDK files
Copy the files prepared in advance jdk8.tar.gz
to docker-demo
this directory
- Write Dockerfile
In docker-demo
this directory, write a Dockerfile
file 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
- Build and run Docker images
In docker-demo
the directory, execute the following command to build the Docker image:
docker build -t java-app:1.0 .
Run this image:
docker run -d -p 8090:8090 --name java-app java-app:1.0
Finally visit in the browser: http://宿主机IP:8090/hello/count
:
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-alpine
as the base image, which is a more lightweight image suitable for scenarios where the container size is reduced.
what is
java:8-alpine
java:8-alpine
It 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 apk
like Ubuntu and CentOS . Due to its streamlined design, Alpine Linux provides a smaller image size, which is very important for containerized applications.apt
yum
Therefore, java:8-alpine
images are a lightweight option that is ideal for running Java applications.
- Modify Dockerfile
In docker-demo
the directory, modify Dockerfile
the file as follows:
# 指定基础镜像
FROM java:8-alpine
# 拷贝 Java 项目的包
COPY ./docker-demo.jar /tmp/app.jar
# 暴露端口
EXPOSE 8090
# 入口,Java 项目的启动命令
CMD ["java", "-jar", "/tmp/app.jar"]
- Rebuild and run the Docker image
In docker-demo
the 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-alpine
as 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.