首页 >Java >java教程 >只需几分钟即可使用 Docker 构建和部署您的第一个 Java 应用程序

只需几分钟即可使用 Docker 构建和部署您的第一个 Java 应用程序

Susan Sarandon
Susan Sarandon原创
2025-01-14 09:42:42202浏览

Building and Deploying Your First Java App with Docker in Just inutes

让我们创建一个简单的 java 应用程序,它返回文本并在 5 分钟内使用 Docker 容器在本地环境的端口 1800 上可用(取决于您的互联网连接速度)。

您随时可以从我的公共存储库获取完整的源代码:
https://github.com/alexander-uspenskiy/simple-service

依赖关系设置

第 1 步:先决条件

  1. 安装 Java 8
  2. 安装 Maven
  3. 安装 Docker
  4. 安装 VS Code 扩展

Mac安装

# Install Homebrew if not present
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Java 8
brew tap homebrew/cask-versions
brew install --cask temurin8

# Install Maven
brew install maven

# Install Docker Desktop
brew install --cask docker

# Install VS Code
brew install --cask visual-studio-code

# Install VS Code Extensions
code --install-extension vscjava.vscode-java-pack
code --install-extension ms-azuretools.vscode-docker

Windows安装

# Install Chocolatey if not present
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Install Java 8
choco install temurin8

# Install Maven
choco install maven

# Install Docker Desktop
choco install docker-desktop

# Install VS Code
choco install vscode

# Install VS Code Extensions
code --install-extension vscjava.vscode-java-pack
code --install-extension ms-azuretools.vscode-docker

项目设置(两个平台)

# Create project structure
mkdir -p simple-service
cd simple-service

VS 代码设置

{
    "java.configuration.runtimes": [
        {
            "name": "JavaSE-1.8",
            "path": "/Library/Java/JavaVirtualMachines/temurin-8.jdk/Contents/Home",
            "default": true
        }
    ],
    "java.configuration.updateBuildConfiguration": "automatic",
    "java.compile.nullAnalysis.mode": "automatic",
    "maven.executable.path": "/usr/local/bin/mvn"
}

验证安装

# Verify Java
java -version

# Verify Maven
mvn -version

# Verify Docker
docker --version

项目设置

# Create Maven project
mvn archetype:generate \
  -DgroupId=com.example \
  -DartifactId=simple-service \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DarchetypeVersion=1.4 \
  -DinteractiveMode=false

创建测试应用程序

最后一步之后,您应该拥有具有预构建结构的简单服务目录。

第 1 步

  1. 更新 pom.xml 文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>simple-service</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>simple-service</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents.client5</groupId>
        <artifactId>httpclient5</artifactId>
        <version>5.4</version>
    </dependency>
</dependencies>
<properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.11.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.example.App</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

第 2 步

向 App.java 添加逻辑

package com.example;

import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.io.IOException;
import java.io.OutputStream;

public class App {
    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(1800), 0);
        server.createContext("/", (exchange -> {
            String response = "Hello from Java!";
            exchange.sendResponseHeaders(200, response.length());
            try (OutputStream os = exchange.getResponseBody()) {
                os.write(response.getBytes());
            }
        }));
        server.setExecutor(null);
        server.start();
        System.out.println("Server started on port 1800");
    }
}

快速解释:

  1. 导入和设置

    • 使用内置的 com.sun.net.httpserver 包
    • 创建简单的 HTTP 服务器,无需外部依赖
    • 在端口 1800 上运行
  2. 服务器配置

HttpServer.create()

  • 创建新的服务器实例

InetSocketAddress(1800)

  • 绑定到端口 1800
  • 0 - 连接队列的默认积压值
  1. 请求处理

createContext("/")

  • 处理对根路径“/”的所有请求
  • Lambda 表达式定义请求处理程序
  • 返回“来自 Java 的你好!”满足所有请求
  1. 响应流程

    • 设置响应代码 200(确定)
    • 设置内容长度
    • 将响应字节写入输出流
    • 使用 try-with-resources 自动关闭流
  2. 服务器启动

setExecutor(null)

  • 使用默认执行器

server.start()

  • 开始监听请求
  • 打印确认消息

第三步

在项目根目录创建Dockerfile:

FROM amazoncorretto:8
WORKDIR /app
COPY target/simple-service-1.0-SNAPSHOT.jar app.jar
EXPOSE 1800
CMD ["java", "-jar", "app.jar"]

步骤 4
创建 docker-compose.yml 来构建容器并将其映射到端口 1800

services:
  app:
    build: .
    ports:
      - "1800:1800"
    restart: unless-stopped

第 5 步
创建build.sh

#!/bin/bash
mvn clean package
docker compose build
docker compose up

并在终端中允许此文件的执行权限:

# Install Homebrew if not present
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Java 8
brew tap homebrew/cask-versions
brew install --cask temurin8

# Install Maven
brew install maven

# Install Docker Desktop
brew install --cask docker

# Install VS Code
brew install --cask visual-studio-code

# Install VS Code Extensions
code --install-extension vscjava.vscode-java-pack
code --install-extension ms-azuretools.vscode-docker

构建并执行应用程序

只需运行

# Install Chocolatey if not present
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Install Java 8
choco install temurin8

# Install Maven
choco install maven

# Install Docker Desktop
choco install docker-desktop

# Install VS Code
choco install vscode

# Install VS Code Extensions
code --install-extension vscjava.vscode-java-pack
code --install-extension ms-azuretools.vscode-docker

您应该已构建项目、创建映像并执行容器。

要测试应用程序,只需打开浏览器,地址为 http://localhost:1800/

快乐编码!

以上是只需几分钟即可使用 Docker 构建和部署您的第一个 Java 应用程序的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn