sbt 中的问题 - scala 项目 dockerisation

Issues in sbt - scala project dockerisation

我是 Scala 世界的新手,我尝试 运行 这个项目来了解 Scala Rest Play 工作流程:https://developer.lightbend.com/guides/play-rest-api/index.html

我能够 运行 使用 sbt run 命令成功完成此项目

/scala/play-scala-rest-api-example$ sbt run 
[info] Loading settings for project play-scala-rest-api-example-build from plugins.sbt ...
[info] Loading project definition from /home/scala/play-scala-rest-api-example/project
[info] Loading settings for project root from build.sbt ...
[info] Loading settings for project docs from build.sbt ...
[info] Set current project to play-scala-rest-api-example (in build file:/home/dominic/scala/play-scala-rest-api-example/)

--- (Running the application, auto-reloading is enabled) ---

[info] p.c.s.AkkaHttpServer - Listening for HTTP on /0:0:0:0:0:0:0:0:9000

(Server started, use Enter to stop and go back to the console...)

我试着把这个项目放在里面docker

FROM ubuntu:latest
MAINTAINER group
RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y  software-properties-common && \
    add-apt-repository ppa:webupd8team/java -y && \
    apt-get update && \
    echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections && \
    apt-get install -y oracle-java8-installer && \
    apt-get clean
RUN echo "deb https://dl.bintray.com/sbt/debian /" | tee -a /etc/apt/sources.list.d/sbt.list
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2EE0EA64E40A89B84B2DF73499E82A75642AC823
RUN apt-get update
RUN apt-get install -y sbt=1.2.8
COPY ./ ./
WORKDIR ./play-scala-rest-api-example
CMD ["sbt","run"]

已成功构建为 docker 图像

但是当我 运行 这个 docker 图像时,它正在打开端口:9000(因为我们 运行 没有 docker)并且端口立即关闭就像以下

--- (Running the application, auto-reloading is enabled) ---

[info] p.c.s.AkkaHttpServer - Listening for HTTP on /0.0.0.0:9000

(Server started, use Enter to stop and go back to the console...)

[info] p.c.s.AkkaHttpServer - Stopping server...

[success] Total time: 614 s, completed Feb 5, 2019 5:11:56 AM
[INFO] [02/05/2019 05:11:56.196] [Thread-2] [CoordinatedShutdown(akka://sbt-web)] Starting coordinated shutdown from JVM shutdown hook

我的问题是为什么我在 docker 运行 时它会关闭?如何让运行这样永远?

您 运行 没有 -it 选项(允许您连接到它的标准输入,就像您在终端中一样)连接您的容器,但您的程序在启动时需要输入("press enter...")。您的程序可能会在 stdin 上等待输入,并且可能会在启动时读取 EOF(文件结尾),导致它终止,进而终止您的容器。

如果你想运行你的容器在后台,在我看来你有两个选择:

1) 运行 您的容器使用 docker run -it -p 9000:9000 <your_other_options> <your_image> 然后使用 CTRL+P 然后 CTRL+Q 将它放到后台。您会看到您的容器在 docker ps 中仍然是 运行ning。要重新附加到它,您可以简单地使用 docker attach <your_container>。当然,如果你想 运行 你的容器,比如你不想手动做 CTRL+P/Q 事情的单元测试服务器,这种方法将不适用。

2) 修改您的服务器,使其 运行 完全在后台运行,无需用户输入。在这种情况下,终止程序的方法是向它发送 SIGINT 信号。这是 CTRL+C 通常做的,也是 docker stop <your_container> 会为你做的。您可能希望在您的 Scala 代码中正确处理此信号,以便您可以执行一些清理而不是突然崩溃。这可以使用 a shutdown hook 来完成。关闭挂钩来自 JVM,不特定于 Scala。您应该注意在关闭挂钩中手动停止任何线程/子进程。

在我看来,第二种方法是最好的,但如果第一种方法适合你,它也更复杂,而且可能有点矫枉过正。