Java 快速开始
代码示例:
https://github.com/TencentCloudBase/cloudbase-examples/tree/master/cloudbaserun/java
点击下方按钮一键部署:
#
第 1 步:编写基础应用首先我们创建一个 Spring Boot 应用。
使用 curl 和 unzip 命令新建一个空 Web 项目:
curl https://start.spring.io/starter.zip \ -d dependencies=web \ -d javaVersion=1.8 \ -d bootVersion=2.3.3.RELEASE \ -d name=helloworld \ -d artifactId=helloworld \ -d baseDir=helloworld \ -o helloworld.zipunzip helloworld.zipcd helloworld
上述命令将创建一个 Spring Boot 项目。
提示
将 src/main/java/com/example/helloworld/HelloworldApplication.java
内容更新如下:
package com.example.helloworld;
import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;
@SpringBootApplicationpublic class HelloworldApplication {
@RestController class HelloworldController {
@GetMapping("/") String hello() { return "Hello World!"; } }
public static void main(String[] args) { SpringApplication.run(HelloworldApplication.class, args); }}
在 src/main/resources/application.properties
中,将服务器端口设置成 8080
:
server.port=8080
以上代码会创建一个基本的 Web 服务器,并监听 8080
端口。
#
第 2 步:将应用容器化在项目根目录下,创建一个名为 Dockerfile
的文件,内容如下:
# 使用官方 maven/Java 8 镜像作为构建环境# https://hub.docker.com/_/mavenFROM maven:3.6-jdk-11 as builder
# 将代码复制到容器内WORKDIR /appCOPY pom.xml .COPY src ./src
# 构建项目RUN mvn package -DskipTests
# 使用 AdoptOpenJDK 作为基础镜像# https://hub.docker.com/r/adoptopenjdk/openjdk8# https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-buildsFROM adoptopenjdk/openjdk11:alpine-slim
# 将 jar 放入容器内COPY --from=builder /app/target/helloworld-*.jar /helloworld.jar
# 启动服务CMD ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/helloworld.jar"]
添加一个 .dockerignore
文件,以从容器映像中排除文件:
Dockerfile.dockerignoretarget/
#
第 3 步(可选):本地构建镜像如果您本地已经安装了 Docker,可以运行以下命令,在本地构建 Docker 镜像:
docker build -t helloworld-java .
构建成功后,运行 docker images
,可以看到构建出的镜像:
REPOSITORY TAG IMAGE ID CREATED SIZEhelloworld-java latest c994813b495b 8 seconds ago 271MB
随后您可以将此镜像上传至您的镜像仓库。