Docker 中运行 SpringBoot 应用

2019-05-1213:41:13后端程序开发Comments2,357 views字数 865阅读模式

创建 SpringBoot 项目

用 Idea 创建一个 SpringBoot 项目,编写一个接口:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/12352.html

package cloud.dockerdemo

import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController

@RestController
class HelloDocker {

    @RequestMapping(value = ["/"], method = [])
    fun hello(): String {
        return "<h1>Hello, Docker!</h1>"
    }
}

这里用的 Kotlin 语言,用 Java 的话,注解是一样的。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/12352.html

下载 OpenJDK 镜像

只用下载 jre 就行,只有 57MB。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/12352.html

docker pull openjdk:8u212-jre-alpine

在项目根目录下建立 Dockerfile

FROM openjdk:8u212-jre-alpine

WORKDIR /home/dev

COPY ./target/*.jar /home/dev/

CMD ["java", "-jar", ""]
  • target 目录就是 maven 打包输出 jar 的目录,把打包的 jar 文件拷贝到容器中。
  • CMD 就是容器启动时执行的命令,即 java -jar

注意这里运行 jar 没有使用 & 符号,因为在 Docker 容器中运行的程序必须是前台的,如果用后台方式运行,命令执行完容器就直接停止了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/12352.html

构建镜像

在终端中把工作目录切换到项目目录,执行:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/12352.html

docker build -t <镜像名称> .

最后的 . 不能掉,它指定了上下文目录为当前目录。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/12352.html

运行容器

docker run --name <容器名称> -d -p 8080:8080 <上一步构建的镜像名称>

运行后,可以使用 docker ps 命令查看是否成功运行。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/12352.html

访问 localhost:8080 访问接口:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/12352.html

Docker 中运行 SpringBoot 应用文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/12352.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/12352.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定