IT

도커 컨테이너를 실행할 때 서비스를 자동으로 시작하는 방법은 무엇입니까?

lottoking 2020. 6. 13. 09:38
반응형

도커 컨테이너를 실행할 때 서비스를 자동으로 시작하는 방법은 무엇입니까?


컨테이너에 MySQL 서버를 설치 하는 Dockerfile 이 있는데 다음과 같이 시작합니다.

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

그러나 MySQL 서비스가 자동으로 시작되지 않으므로 컨테이너 내에서 수동으로 실행해야합니다.

service mysql start

도커 컨테이너를 실행할 때 MySQL 서비스를 자동으로 시작하려면 어떻게합니까?


먼저, 당신 문제 가 있습니다 Dockerfile:

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

Docker 이미지는 실행중인 프로세스를 저장하지 않습니다. 따라서 RUN명령은 docker build단계 중에 만 실행 되고 빌드가 완료된 후에 중지됩니다. 대신 아래와 같이 CMD또는 ENTRYPOINT명령을 사용하여 컨테이너를 시작할 때 명령을 지정해야 합니다.

CMD mysql start

둘째, 도커 컨테이너는 계속 실행하기 위해 프로세스 (마지막 명령)가 필요합니다. 그렇지 않으면 컨테이너가 종료 / 중지됩니다. 따라서 일반 service mysql start명령은 Dockerfile에서 직접 사용할 수 없습니다.

해결책

프로세스를 계속 실행하는 세 가지 일반적인 방법이 있습니다.

  • 그런 다음에 service명령을 사용 하고 끝이 아닌 명령을 추가하십시오.tail -F

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

출력 된 로그를 docker가 액세스 할 수 있도록 단일 서비스를 실행하는 경우에 종종 선호됩니다.

  • 또는 전경 명령을 사용 하여이 작업을 수행하십시오.

    CMD /usr/bin/mysqld_safe
    

이 같은 스크립트가있는 경우에만 작동합니다 mysqld_safe.

  • 또는 스크립트를 감싸서 start.sh끝내십시오.

    CMD /start.sh
    

명령이 일련의 단계를 다시 수행해야하고 실행 상태를 유지해야하는 경우에 가장 좋습니다 /start.sh.

노트

초보자는 사용 supervisord하지 않는 것이 좋습니다. 솔직히, 그것은 과잉입니다. 컨테이너에 단일 서비스 / 단일 명령을 사용하는 것이 훨씬 좋습니다.

BTW : https://registry.hub.docker.com 에서 기존 MySQL 도커 이미지를 참조하십시오.


Dockerfile에서 마지막 줄에 추가 하십시오 .

ENTRYPOINT service ssh restart && bash

그것은 나를 위해 작동

그리고 이것은 결과입니다 :

root@ubuntu:/home/vagrant/docker/add# docker run -i -t ubuntu
 * Restarting OpenBSD Secure Shell server sshd   [ OK ]                                                                      
root@dccc354e422e:~# service ssh status
 * sshd is running

항상 더 읽기 쉬운 것으로 밝혀진 또 다른 방법이 있습니다.

rabbitmq와 mongodb를 실행할 때 다음 CMD과 같이 보일 것이라고 가정하십시오.

CMD /etc/init.d/rabbitmq-server start && \
    /etc/init.d/mongod start

트릭 CMD하나만 가질 수 있기 때문에 Dockerfile모든 명령을 연결 &&한 다음 \각 명령에 사용 하여 새 줄을 시작하는 것입니다.

많은 것들을 추가하게되면 모든 명령을 스크립트 파일에 넣고 @ larry-cai가 제안한 것처럼 시작하십시오.

CMD /start.sh

단순한! dockerfile 끝에 추가하십시오.

ENTRYPOINT service mysql start && /bin/bash

제 경우에는 MYSQL 백엔드 데이터베이스에 연결하는 docker 컨테이너 내에서 Apache2가 제공하는 PHP 웹 응용 프로그램이 있습니다. Larry Cai의 솔루션은 약간만 수정되었습니다. entrypoint.sh서비스를 관리 하는 파일을 만들었습니다 . entrypoint.sh컨테이너가 시작될 때 실행할 명령이 둘 이상있을 때를 만드는 것이 도커를 부트 스트랩하는 더 확실한 방법이라고 생각합니다.

#!/bin/sh

set -e

echo "Starting the mysql daemon"
service mysql start

echo "navigating to volume /var/www"
cd /var/www
echo "Creating soft link"
ln -s /opt/mysite mysite

a2enmod headers
service apache2 restart

a2ensite mysite.conf
a2dissite 000-default.conf
service apache2 reload

if [ -z "$1" ]
then
    exec "/usr/sbin/apache2 -D -foreground"
else
    exec "$1"
fi

ssh 서비스를 자동으로 시작하려고 할 때도 같은 문제가 있습니다. 나는 그 추가를 발견

/etc/init.d/ssh 시작
~ / .bashrc
그것을 해결할 수는 있지만 bash로 열면됩니다.


도커 컨테이너가 실행될 때마다 MySQL 서비스를 자동으로 시작하는 방법은 다음과 같습니다.

On my case, I need to run not just MySQL but also PHP, Nginx and Memcached

I have the following lines in Dockerfile

RUN echo "daemon off;" >> /etc/nginx/nginx.conf
EXPOSE 80
EXPOSE 3306
CMD service mysql start && service php-fpm start && nginx -g 'daemon off;' && service memcached start && bash

Adding && bash would keep Nginx, MySQL, PHP and Memcached running within the container.


The following documentation from the Docker website shows how to implement an SSH service in a docker container. It should be easily adaptable for your service:

A variation on this question has also been asked here:


I add the following code to /root/.bashrc to run the code only once,

Please commit the container to the image before run this script, otherwise the 'docker_services' file will be created in the images and no service will be run.

if [ ! -e /var/run/docker_services ]; then
    echo "Starting services"
    service mysql start
    service ssh start
    service nginx start
    touch /var/run/docker_services
fi

docker export -o <nameOfContainer>.tar <nameOfContainer>

Might need to prune the existing container using docker prune ...

Import with required modifications:

cat <nameOfContainer>.tar | docker import -c "ENTRYPOINT service mysql start && /bin/bash" - <nameOfContainer>

Run the container for example with always restart option to make sure it will auto resume after host/daemon recycle:

docker run -d -t -i --restart always --name <nameOfContainer> <nameOfContainer> /bin/bash

Side note: In my opinion reasonable is to start only cron service leaving container as clean as possible then just modify crontab or cron.hourly, .daily etc... with corresponding checkup/monitoring scripts. Reason is You rely only on one daemon and in case of changes it is easier with ansible or puppet to redistribute cron scripts instead of track services that start at boot.


This not works CMD service mysql start && /bin/bash

This not works CMD service mysql start ; /bin/bash ;

-- i guess interactive mode would not support foreground.

This works !! CMD service nginx start ; while true ; do sleep 100; done;

This works !! CMD service nginx start && tail -F /var/log/nginx/access.log

beware you should using docker run -p 80:80 nginx_bash without command parameter.

참고URL : https://stackoverflow.com/questions/25135897/how-to-automatically-start-a-service-when-running-a-docker-container

반응형