[英]How to run Docker container from Java project?
How to run a docker container from java code?如何从 java 代码运行 docker 容器? I'm trying to make a SaaS using docker, once the user logs in, I should start a memcached container from java code, this solution doesn't work:
我正在尝试使用 docker 创建一个 SaaS,一旦用户登录,我应该从 java 代码启动一个 memcached 容器,这个解决方案不起作用:
Process p = Runtime.getRuntime().exec("docker images");
Docker cmds run usually on git bash, not on cmd. Docker cmds 通常在 git bash 上运行,而不是在 cmd 上运行。
PS: I'm using docker on windows .
PS:我在windows上使用 docker 。
You can do it using https://github.com/docker-java/docker-java .您可以使用https://github.com/docker-java/docker-java来完成。 It allows you to build a custom image and run it from java
它允许您构建自定义图像并从 java 运行它
I assume you are using Docker Toolbox for Windows.我假设您正在使用适用于 Windows 的 Docker 工具箱。
The docker command does not take a capital D
. docker 命令不使用大写字母
D
。 Maybe try with也许试试
Process p = Runtime.getRuntime().exec("docker images");
but as you are probably running this code on Windows, that might work anyway.但由于您可能在 Windows 上运行此代码,所以它可能仍然有效。
Another thing to consider is the value of the DOCKER_HOST
environment variable which must be set accordingly to instruct the docker client how to communicate with the docker engine.另一件需要考虑的事情是
DOCKER_HOST
环境变量的值,必须相应地设置它以指示 docker 客户端如何与 docker 引擎通信。
In your case the docker client is run on Windows while the docker engine runs inside a virtual machine living in VirtualBox.在您的情况下,docker 客户端在 Windows 上运行,而 docker 引擎在 VirtualBox 中的虚拟机内运行。
The shell provided by Runtime.getRuntime().exec()
won't have the DOCKER_HOST
environment variable set. Runtime.getRuntime().exec()
提供的 shell 不会设置DOCKER_HOST
环境变量。
Another way is to use the --host
or -H
docker client option to specify how to connect to your docker engine:另一种方法是使用
--host
或-H
docker 客户端选项来指定如何连接到您的 docker 引擎:
Process p = Runtime.getRuntime().exec("docker --host=tcp://<some IP>:2376 images");
I'm sorry guys, when I open a new shell (client), I have to configure it in order to know how to connect to the docker daemon that is running in the virtualbox.对不起,伙计们,当我打开一个新的 shell(客户端)时,我必须配置它才能知道如何连接到在 virtualbox 中运行的 docker 守护进程。 I had to run cmds that set the shell environment, because the quickstart terminal does it automatically.
我必须运行设置 shell 环境的 cmds,因为快速启动终端会自动执行它。 So I had to run the following and then paste the output back into my cmd shell:
所以我必须运行以下命令,然后将输出粘贴回我的 cmd shell:
docker-machine env --shell cmd default
Now it works perfectly.现在它完美地工作。
Update (thanks to @thaJeztah): It's better to use Java libraries to connect directly to the docker daemon.更新(感谢@thaJeztah):最好使用 Java 库直接连接到 docker 守护进程。
Link to API https://docs.docker.com/engine/reference/api/remote_api_client_libraries/链接到 API https://docs.docker.com/engine/reference/api/remote_api_client_libraries/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.