我是 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
选项(允许您像在终端中一样连接到其标准输入),但您的程序在启动时需要输入(“按 Enter...”)。您的程序可能等待 stdin
上的输入并可能在启动时读取 EOF(文件结尾),导致其终止,从而终止您的容器。
如果您想在后台运行容器,在我看来您有两个选择:
1) 使用 docker run -it -p 9000:9000 <your_other_options> <your_image>
运行容器然后使用 CTRL+P
将其置于后台然后CTRL+Q
。您将看到您的容器仍在 docker ps
中运行。要重新连接它,您可以简单地使用 docker attach <your_container>
。当然,如果您想在单元测试服务器上运行容器,而您不想手动执行 CTRL+P/Q
,则此方法将不适用。东西。
2) 修改您的服务器,使其可以完全在后台运行,无需用户输入。在这种情况下,终止程序的方法是向其发送 SIGINT
信号。这就是CTRL+C
通常会这样做,还有什么docker stop <your_container>
会为你做的。您可能希望在 Scala 代码中正确处理此信号,以便可以执行一些清理操作而不是突然崩溃。这可以使用 a shutdown hook 来完成。关闭 Hook 来自 JVM,不是 Scala 特有的。您应该注意手动停止关闭 Hook 中的任何线程/子进程。
在我看来,第二种方法是最好的,但也更复杂,如果第一种方法适合您,则可能有点过分了。
关于scala - sbt - scala 项目 dockerization 中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54528065/