运行docker容器时如何自动启动服务? [英] How to automatically start a service when running a docker container?

查看:3281
本文介绍了运行docker容器时如何自动启动服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Dockerfile 在容器中安装MySQL服务器,然后我开始这样做:

  sudo docker运行-t -i 09d18b9a12be / bin / bash 
 服务mysql start 

如何自动启动MySQL服务当我运行docker容器时?

解决方案

问题
在你的 Dockerfile

 运行服务mysql restart&& /tmp/setup.sh 

首先,docker图像不会对您正在运行的进程进行快照,您的 RUN 命令只在 docker build 阶段运行,您需要指定在容器开始使用 CMD 或 ENTRYPOINT 命令如下

  CMD mysql start 

其次Docker容器需要进程(最后一个命令)继续运行,否则容器将出口。因此,正常的服务mysql start 命令不能直接在Dockerfile中使用



解决方案 :为了保持这个过程的运行:



通常情况下,您的 Dockerfile有三种方式


  • 使用服务命令,并附加非终止命令,如 tail -F

      CMD服务mysql start&& tail -F /var/log/mysql/error.log 


  • 或使用foreground命令这样做

      CMD / usr / bin / mysqld_safe 


  • 或将脚本包装到 start.sh 中,并将其结束

      CMD /start.sh 




对于已启动的用户,不建议使用 supervisord ,更好地为一个容器使用单一服务。



BTW:请检查 https://registry.hub.docker.com 以查找现有的mysql docker图像参考


I have a Dockerfile to install MySQL server in a container, which I then start like this:

sudo docker run -t -i 09d18b9a12be /bin/bash

But the MySQL service does not start automatically, I have to manually run (from within the container):

service mysql start

How do I automatically start the MySQL service when I run the docker container?

解决方案

Problem In your Dockerfile

RUN service mysql restart && /tmp/setup.sh

Firstly, docker images doesn't snapshot your running process, your RUN command just run during docker build phase, you need to specify the command to run when container started using CMD or ENTRYPOINT command like below

CMD mysql start

Secondly Docker container needs the process (last command) keep running, otherwise the container will exit. Therefore normal service mysql start command can't be used directly in Dockerfile

Solution: In order to keep the process running:

There are three ways for your Dockerfile normally

  • Using service command and append non-end command after that like tail -F

    CMD service mysql start && tail -F /var/log/mysql/error.log
    

  • or use foreground command to do this

    CMD /usr/bin/mysqld_safe
    

  • or wrap your scripts into start.sh and put this in end

    CMD /start.sh
    

For started user, supervisord is not recommended, better to use single service for one container.

BTW: please check https://registry.hub.docker.com for existing mysql docker images for reference

这篇关于运行docker容器时如何自动启动服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆