在 docker 容器中自动运行服务 [英] Run a service automatically in a docker container
问题描述
我正在设置一个简单的图像:一个包含 Riak(一个 NoSQL 数据库)的图像.该图像以 riak start
作为 CMD 启动 Riak 服务.现在,如果我使用 docker run -d quintenk/riak-dev
作为守护进程运行它,它会启动 Riak 进程(我可以在日志中看到).但是,它会在几秒钟后自动关闭.如果我使用 docker run -i -t quintenk/riak-dev/bin/bash
运行它,则 riak 进程不会启动(更新:请参阅答案以获取对此的解释).事实上,根本没有任何服务在运行.我可以使用终端手动启动它,但我希望 Riak 自动启动.我认为其他服务也会出现这种行为,Riak 只是一个例子.
I'm setting up a simple image: one that holds Riak (a NoSQL database). The image starts the Riak service with riak start
as a CMD. Now, if I run it as a daemon with docker run -d quintenk/riak-dev
, it does start the Riak process (I can see that in the logs). However, it closes automatically after a few seconds. If I run it using docker run -i -t quintenk/riak-dev /bin/bash
the riak process is not started (UPDATE: see answers for an explanation for this). In fact, no services are running at all. I can start it manually using the terminal, but I would like Riak to start automatically. I figure this behavior would occur for other services as well, Riak is just an example.
因此,运行/重启容器应该会自动启动 Riak.设置它的正确方法是什么?
So, running/restarting the container should automatically start Riak. What is the correct approach of setting this up?
作为参考,这里是可以用来创建图像的 Dockerfile(更新:使用所选答案更改):
For reference, here is the Dockerfile with which the image can be created (UPDATE: altered using the chosen answer):
FROM ubuntu:12.04
RUN apt-get update
RUN apt-get install -y openssh-server curl
RUN curl http://apt.basho.com/gpg/basho.apt.key | apt-key add -
RUN bash -c "echo deb http://apt.basho.com precise main > /etc/apt/sources.list.d/basho.list"
RUN apt-get update
RUN apt-get -y install riak
RUN perl -p -i -e 's/(?<={http,s[s{")127.0.0.1/0.0.0.0/g' /etc/riak/app.config
EXPOSE 8098
CMD /bin/riak start && tail -F /var/log/riak/erlang.log.1
-f 根据他的评论在 CMD 中更改为 -F
-f changed to -F in CMD in accordance to sesm his remark
使用 Docker 一段时间后,我养成了使用 supervisord 来调整进程的习惯.如果您需要示例代码,请查看 https://github.com/Krijger/docker-cookbooks.我使用我的主管形象作为我所有其他形象的基础.我在博客上使用主管 此处.
After working with Docker for some time I picked up the habit of using supervisord to tun my processes. If you would like example code for that, check out https://github.com/Krijger/docker-cookbooks. I use my supervisor image as a base for all my other images. I blogged on using supervisor here.
推荐答案
要保持 docker 容器运行,您需要在前台保持一个进程处于活动状态.
To keep docker containers running, you need to keep a process active in the foreground.
因此您可能可以将 Dockerfile 中的最后一行替换为
So you could probably replace that last line in your Dockerfile with
CMD /bin/riak console
甚至
CMD /bin/riak start && tail -F /var/log/riak/erlang.log.1
请注意,CMD 语句不能有多行,只能运行最后一行.
Note that you can't have multiple lines of CMD statements, only the last one gets run.
这篇关于在 docker 容器中自动运行服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!